When you have to access a "member variable"/field in a class, is it good practice to access it directly or call the getter and setter? and why?
-
Read this, it answers the "Why?" part. http://stackoverflow.com/questions/1568091/why-use-getters-and-setters – RCE Dec 07 '11 at 00:36
4 Answers
Call the setter/getter rather than accessing directly. That way any extra required code in the setter/getter will be run.

- 295,962
- 43
- 465
- 541
I see almost only benefits in making your fields private and only provide access through a getter and possibly a setter
- controlled access. If you only want to provide read access, or only write access you can only achieve this by using getters/setters
- if you want to fire
PropertyChangeEvents
for bean properties, you can include this code in your setter. Otherwise all calls which modify this field directly should trigger a change event as well - I personally find it easier to discover in my IDE who modifies the field. The only direct access to the field is in the class (since it is a private field), and all external changes go through the setter. This allows for faster debugging than having to use a field watchpoint
- subclasses who want to do something extra when the field change can override the setter, call
super.set
and do something extra
The only possible drawback I can think of is that it requires a bit more code to write (for the getters and setters), and a bit more code for accessing the field from outside the class. But with the current IDEs is this a pretty lame excuse
Getter/ Setter allows for lazy instantiation, which is often a way to go. Additionally, this way you have a controlled access to your variables (both for yourself and as part of any API you may want to expose); ability to hide implementation of initialization etc are also very important.
The biggest benefits of S/G in my opinion is reduced risk of someone modifying it without your control. A small example .. consider that a getter may give you .. a copy
of the original instead of an original.
Benefits are multiple, when given a choice, choose setter/ getter for the benefits of data encapsulation and more control.

- 92,517
- 154
- 335
- 470
If it is a member of the calling class, access it directly. Otherwise use the getter/setter methods.
Why? You should not be creating getter/setter methods just so that the calling class can access its own members. Otherwise you should use the getter/setter methods for the reasons elaborated by others.

- 10,725
- 2
- 30
- 58