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?
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With