Getter Setter: To Use or Not to Use?
An experienced Java developer goes over when, and when not, to use getters and setters as well as accessor methods in your codebase.
Join the DZone community and get the full member experience.
Join For FreeJava Getter Setter
Why do we keep instance variables private? We don’t want other classes to depend on them. Moreover, it requires flexibility to change a variable’s type or implementation on a whim or an impulse. Why, then, do programmers automatically add getters and setters to their objects, exposing their private variables as if they were public?
Accessor Methods
Accessors (also known as getters and setters) are methods that let you read and write the value of an instance variable of an object.
public class AccessorExample {
private String attribute;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}
Why Accessors?
There are actually many good reasons to consider using accessors rather than directly exposing the fields of a class.
Getter and Setters make APIs more stable. For instance, consider a field public in a class which is accessed by other classes. Later on, if we want to add any extra logic while getting and setting the variable, this will impact the existing client that uses the API. So any changes to this public field will require a change to each class that refers to it. On the other hand, with accessor methods, one can easily add some logic, like caching some data or lazy initialization.
Accessor methods also allow us to fire a property changed event if the new value is different from the previous value.
Another advantage of using setters to set values is that we can use the method to preserve an invariant or perform some special processing when setting values.
All this will be seamless to the class that gets the value using the accessor method.
Should I Have Accessor Methods for all my Fields?
Fields can be declared public for package-private or private nested classes. Exposing fields in these classes produces less visual clutter compared to the accessor method approach, both in the class definition and in the client code that uses it.
If a class is package-private or is a private nested class, there is nothing inherently wrong with exposing its data fields — assuming they do an adequate job of describing the abstraction provided by the class.
Such code is restricted to the package where the class is declared, while the client code is tied to a class's internal representation. We can change it without modifying any code outside that package. Moreover, in the case of a private nested class, the scope of the change is further restricted to the enclosing class.
Another example of a design that uses public fields is JavaSpace entry objects. Ken Arnold described the process they went through to decide to make those fields public instead of private with get and set methods here.
Now, this sometimes makes people uncomfortable because they've been told not to have public fields and that public fields are bad. Rules have reasons. And the reason for the private data rule doesn't apply in this particular case. It is a rare exception to the rule. I also tell people not to put public fields in their objects, but exceptions exist. This is an exception to the rule because it is simpler and safer to just say it is a field. We sat back and asked: why is the rule thus? Does it apply? In this case, it doesn't.
Private Fields + Public Accessors == Encapsulation
Consider the example below:
xxxxxxxxxx
public class A {
public int a;
}
Usually, this is considered bad coding practice as it violates encapsulation. The alternate approach is:
xxxxxxxxxx
public class A {
private int a;
public void setA(int a) {
this.a =a;
}
public int getA() {
return this.a;
}
}
It is argued that this encapsulates the attribute. Now is this really encapsulation?
The fact is, getters/setters have nothing to do with encapsulation. Here, the data isn't more hidden or encapsulated than it was in a public field. Other objects still have intimate knowledge of the internals of the class. Changes made to the class might ripple out and enforce changes in dependent classes. Getters and setters, in this way, are generally breaking encapsulation. A truly well-encapsulated class has no setters and preferably no getters either. Rather than asking a class for some data and then computing something with it, the class should be responsible for computing something with its data and then return the result.
Consider the example below:
xxxxxxxxxx
public class Screens {
private Map screens = new HashMap();
public Map getScreens() {
return screens;
}
public void setScreens(Map screens) {
this.screens = screens;
}
// remaining code here
}
If we need to get a particular screen, we write some code like below:
xxxxxxxxxx
Screen s = (Screen)screens.get(screenId);
There are things worth noticing here...
The client needs to get an Object from the Map and cast it to the right type. Moreover, the worst is that any client of the Map has the power to clear it, which may not be the case we usually want.
An alternative implementation of the same logic is:
xxxxxxxxxx
public class Screens {
private Map screens = new HashMap();
public Screen getById(String id) {
return (Screen) screens.get(id);
}
// remaining code here
}
Here, the Map instance and the interface at the boundary (Map) are hidden.
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 a 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.
All fields should be kept private, but, setters should only be kept private when it makes sense, which makes that object Immutable. Adding an unnecessary getter reveals an internal structure, which is an opportunity for increased coupling. To avoid this, every time before adding the accessor, we should analyze if we can encapsulate the behavior instead.
Let’s take another example:
xxxxxxxxxx
public class Money {
private double amount;
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
//client
Money pocketMoney = new Money();
pocketMoney.setAmount(15d);
double amount = pocketMoney.getAmount(); // we know its double
pocketMoney.setAmount(amount + 10d);
}
With the above logic, later on, if we assume that double is not the right type to use, and we should use BigDecimal instead, then the existing client that uses this class also breaks.
Let’s restructure the above example:
xxxxxxxxxx
public class Money {
private BigDecimal amount;
public Money(String amount) {
this.amount = new BigDecimal(amount);
}
public void add(Money toAdd) {
amount = amount.add(toAdd.amount);
}
// client
Money balance1 = new Money("10.0");
Money balance2 = new Money("6.0");
balance1.add(balance2);
}
Now instead of asking for a value, the class has a responsibility to increase its own value. With this approach, the change request for any other datatype in the future requires no changes to the client code.
Conclusions
Use of accessors to restrict direct access to a field variable is preferred over the use of public fields, however, making getters and setters 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 to a 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.
More Reading
Published at DZone with permission of Muhammad Ali Khojaye, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments