is getter method call to access variable better than direct variable access within a class

In Java it is a convention to access all fields via getter/setters from outside the class. From inside the class, you usually access fields directly. However, you can also access them via getter/setter is you want to.

It is important to know that this is just a convention. Many other programming languages don't have such strict rules or other concepts. So you are not forced to do that. But it is a good practice.

And: Don't mind performance! Using getters/setters will not affect the performance of your app. The JVM/Java is designed to work exactly like this. Every JVM will optimize your code and handle getters/setters in a very effective way. Try to write clear and good readable code.


I will answer your question in three parts :

  1. Direct access (public members) is the worst solution :

    A public member can be accessed from outside the class, which for practical considerations means "potentially anywhere". If something goes wrong with a public field, the culprit can be anywhere, and so in order to track down the bug, you may have to look at quite a lot of code.

  2. Encapsulation ( private members ) :

    A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort by a factor of 1000.

  3. Getters and Setters are highly Overused :

    Creating private fields and then using the IDE to automatically generate getters and setters for all these fields is almost as bad as using public fields.

    One reason for the overuse is that in an IDE it’s just now a matter of few clicks to create these accessors. The completely meaningless getter/setter code is at times longer than the real logic in a class and you will read these functions many times even if you don't want to.

CONCLUSION:

Use of accessors (getters and setters ) to restrict direct access to field variable is preferred over the use of public fields, however, making getters and setter for each and every field is overkill. It also depends on the situation though, sometimes you just want a dumb data object. Accessors should be added for field where they're really required. A class should expose larger behavior which happens to use its state, rather than a repository of state to be manipulated by other classes.

Tags:

Java

Class