Search code examples
privateencapsulationgetter-setter

Encapsulation - Why I am using getter setter to make my data members public if I already declare them private in class


I just want to ask, we are having one class, in which we have two private data members say:

class Employee{
private int empid;
private String empname;

}

I am declaring them private that means I can use them in Employee class only. So what is the need to create getter setter for both the data members and making them public.

Hope you got my problem.


Solution

  • This is an excellent question. Often you see code examples that make members private but exposing them via a getter/setter pair, without the getter/setter doing anything else than setting the corresponding member.

    In my book this is not encapsulation at all. You are no better of than just making the members public. Although a lot of people are uneasy to do that, they would happily provide accessors automatically for all their members.

    One reason to do provide accessors is the ability to do input validation. E.g. if you empIds have a checksum, you could enforce it in the setter. Something that is not possible with direct access to the member.

    In my opinion it would be better to think about the role this object will play and see how it can achieve that role with a minimum of accessors. Otherwise your code will probably violate the Law of Demeter.