Using getter / setter inside a class is good or bad practice?

Using getter / setter in the inner class code instead of directly accessing an instance variable is good or bad practice? At least for setters, you can add an extra code to confirm the value, but for getters, is this just overhead? How smart is the Java compiler if my getters / seters just set / get the value directly, will Java optimize my code and replace getters / setters with direct access to instance variables, so there is no way to call overhead?

+4
source share
3 answers

Most often, access the field directly. The value of the setFieldName method is more obvious to programmers using your code in other classes. With hidden implementation details, they may not understand which ranges of values ​​are acceptable, so keeping private fields and forcing other developers to use the setter makes sense. But inside your own class, the case of using a setter is much weaker. If you look at the source for the java API, you will find that the getter / setter methods are not commonly used in a class.

+5
source

There is no need to do this inside the class if you do not want to perform additional operations on these getters / setters. Access to class members can be direct for the class inside:

  • The reason for hiding is mainly hiding the implementation (and there is no need to hide the implementation from the class itself)
  • Recipients and setters directly access the elements, so you can simply call them to avoid accessing the elements directly, something ... redundant.

As for performance - I honestly believe that in most cases you should not think about it, you should decide whether to call the method or access directly in terms of readability, scalability and maintenance, and not in terms of another nano second or not. This approach pays off in the long run. There are places for optimization, and you should be effective, but keeping the code clear and supported is much more important if the code base is more than 20 lines.

+7
source

Direct access is good. However, no one can say that access to getter / setter is bad, inside the same class. If you are developing a Java bean, you will definitely understand what I'm saying. Think you're trying to get JTextField user input as a string. In this case, the getter methods will allow you to do many things, including truncating strings, trimming, uppercase letters, lowercase letters, etc. If you are trying to do this all by simply accessing a direct variable (for example: String s = textField.getText ()), it will be difficult for you to do this. So, what I think is good or bad depends on the situation and what you are developing.

+1
source

Source: https://habr.com/ru/post/1412175/


All Articles