java - Which way of setting fields value is better and why? -
this question can stupid, want know, there difference?
class a{ // common code private int field; public void setfield(int field){ this.field = field; } //way 1 public a(int field){ this.field = field; } //way 2 public a(int field){ setfield(field); } }
way 2 better because gives unified way of setting variable value. brings in risk, because you're calling overrideable method in constructor. right syntax using final keyword:
public final void setfield(int field){ this.field = field; } //way 2 public a(int field){ setfield(field); }
with final
method not overriden. if can not afford have final method, don't call setter in constructor. it's strange override setter.
this because may want change setter later:
- add argument checks , throw
illegalargumentexception
when required. - add counter
- notify observers (in observable pattern)
- make synchronized block provide thread-safety
- ...
and have in single place. implementation of dry principle.
public final synchronized void setfield(int field){ if (0 <= field && field <= max_value) { this.field = field; } else { throw new illegalargumentexception(); } } //still has benefits of setter public a(int field){ setfield(field); } = new a(-1) //throws illegalargumentexception
don't worry optimization , expenses of method call. jvm can optimize such code inlining methods.
what makes development slower searching bug. method helps make less mistakes , easier maintain code.
Comments
Post a Comment