user3104459 user3104459 - 5 months ago 8
Java Question

Is it a good coding practice to use getter for accessing private instance variables

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());
}
}

Answer

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.

Comments