Why use getters and setters

In the previous article JavaBean Standard we explained the JavaBean Specification. In the current post we shall discuss JavaBeans and why use getters and setters. This is one of the favorite topic of Interviewers for 1-3 yrs experience candidates.

So the real pressing question is Why should we need getters & setters? which basically do nothing,  lets consider the below Employee class which has private field name and public getters & setters for name also it has a public field department without any getters & setters for the same.

The below code lines does the similar operation of setting value to particular field.

So, what is the difference between the 2nd and 3rd statement?

From task perspective they perform similar thing i.e. updating a variable with some value.

However there are significant differences which are.

  1. Making a field public we are providing direct access to the field, through which anyone can set a undesirable or null value without any restrictions, whereas when we use a setter, the setter method is the single point of contact & indirect access for updating the field, we can restrict what values are acceptable for field via some validations such as a null check before setting the value. By doing so everyone intending to update the field has to abide by the validation rule.
  2. getters & setters act as one and only entry & exit point for the field. There can also be a logic added to getter wherein we decide to return the clone of the object rather than returning the actual reference.
  3. Usually most of the times getters & setters method do not have any validation checks inside them, we do that to provision any validation to be added in future.
  4. Many people argue to say that since we don’t have anything inside the getters & setters most of the time, why should we ever be writing them instead making the field public. But it is always better to have a few lines of code extra to support future validation rather than requiring to change each and every instance of access to public field.

Leave a Reply

Your email address will not be published. Required fields are marked *