Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getter / setter inside a class - good or bad practice? [closed]

Using a getter/setter in the internal code of a class instead of accessing the instance variable directly, is it good or bad practice? At least for setters one could add additional code validating the value, but for the getters it's just overhead? How intelligent is the Java compiler, if my getters/setters just set/get the value directly, will Java optimize my code and replace the getters/setters by direct access to the instance variables, so there's no method calling overhead?

like image 698
stefan.at.wpf Avatar asked May 12 '12 18:05

stefan.at.wpf


Video Answer


2 Answers

It is more common to access the field directly. The value of a setFieldName method is more obvious for programmers using your code in other classes. With the implementation details hidden, they might not realize what ranges of values are acceptable, so keeping fields private and forcing other developers to go through a setter makes sense. But inside your own class, the case for using a setter is much weaker. If you look at the source for the java API you'll find that getter / setter methods are generally not used within a class.

like image 156
Thorn Avatar answered Sep 29 '22 09:09

Thorn


There is no need to do that inside a class, unless want to perform additional operations in those getters / setters. The access to the class members can be direct to the class internally, as:

  • The reason for hiding is mainly to hide the implementation (and there's no need to hide the implementation from the class itself)
  • The getters and setters access the members directly, so to call them just to avoid access the members directly is somewhat, umm... redundant.

Regarding performance - I honestly think that in most cases, you shouldn't think about it, you should decide whether to call a method or access directly in terms of readability, scalability and maintenance, not in terms of whether it will take another nano second or not. This approach pays off in the long run. There are places for optimizations, and you should be efficient, but keeping your code clear and maintainable is much more important once the code base is over 20 lines.

like image 36
MByD Avatar answered Sep 29 '22 11:09

MByD