Shree Naath Shree Naath - 3 months ago 12
Java Question

What is the difference between using the constructor and using getters and setters?[got the answer]

Using a constructor :

Person(String name) {
this.name = name;
}


Using getters and setters :

void setName(String name){
this.name=name;
}
String getName(){
return this.name;
}


Please do include all the differences if possible. And suggest me which is better..

Answer

Immutability makes the code better (thread-safe, more readable, safer in general) and setters are inherently the contrary of immutability.

I don't like setters, it makes things much more complicated because the value of the field is difficult to determine in certain code paths where the object is passed around in many places. It's much better practice to set all attributes to final when possible.

Rule of thumb:

  • make all fields final by default (therefore, no setter)
  • if one field absolutely cannot be final, then only make it non-final
  • if the same field absolutely must be modified from outside, then only add a setter

If you apply that rule, believe me that you will end up using practically no non-final fields and even less setters.

Comments