Recently I got a code review comment to use getter method for accessing private instance variable inside methods of same class. Is it really a good practice? I feel that it is adding unnecessary complication in code. What is the recommended way?
public class SomeClass {
String abc;
public boolean compare(SomeClass otherClass) {
otherClass.getAbc().equals(abc);
}
}
public class SomeClass {
String abc;
public boolean compare(SomeClass otherClass) {
otherClass.getAbc().equals(getAbc());
}
}
I see a very specific problem with your first approach. You're using getters inconsistently.
public boolean compare(SomeClass otherClass) {
otherClass.getAbc().equals(abc);
//.getAbc() for one, but direct access for the other!!
}
You have to compare apples to apples for an equals method, and if one of your variables is retrieved for comparison using a getter (which I assume is public and can be overridden) and the other is retrieved directly from a private variable (which cannot be overridden), then you've made your code much more fragile than it needs to be. What if somebody extends your class and changes the getter method? Your code will be hosed. Therefore, use a getter on both or none.
With that in mind, either of these is better than your original, since the behavior is more stable:
public boolean compare(SomeClass otherClass) {
otherClass.abc.equals(abc);
}
public boolean compare(SomeClass otherClass) {
otherClass.getAbc().equals(getAbc());
}
For general purposes, it depends on how you're using the data. David's answer lists some resources for general usage of getters.
It's entirely possible that your reviewer was only talking about the general case, but I think they may have just communicated the problem poorly.
In theory, using getters and setters within the class could provide code reuse, for example if the setter does some kind of range checking which is useful within the class as well. In practice I have never seen a case where this was really beneficial.
Ideally a class should not have setters and getters at all.
Why no setters? Because they provide mutable state which causes lots of issues. Class variables should ideally be assigned in the constructor and never change later.
Why no getters? Because a class should act as a unit. The point of creating a class is not just to provide a temporary container for different variables just to extract them later, one-by-one. That's not encapsulation.
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