Encapsulation – why do we need it when setters are already public? [duplicate]

Is it because we do not want others to know the exact way we are
storing data or managing data on the back-end?

Yes, that’s the point. It is related to the concepts of abstraction and information hiding too.

You provide a public setter that when invoked by the class client will have the effect that you have documented. It is none of the client’s business how this effect is actually achieved. Are you modifying one of the class attributes? Ok, let the client know that, but not the fact that you are actually modifying a variable. In the future, you could want to modify your class so that instead of a simple backup variable it uses something completely different (a dictionary of attributes? An external service? Whatever!) and the client will not break.

So your setter is an abstraction that you provide to the client for “modify this class attribute”. At the same time you are hiding the fact that you are using an internal variable because the client doesn’t need to know that fact.

(Note: here I’m using the word “attribute” as a generic concept, not related to any concrete programming language)

Leave a Comment