Is it better use getter methods or to access private fields directly when overriding toString?

java, tostring

Solution

Use getters, if you have them!

Maybe, one day you change the code so that a getter will not only return the fields value but do something more or create the result in a different way. Then you'll be more then happy that you used getters consistently.

But as usual, there are excemptions from my advice - what do you expect from the toString() method if you allow overriding of the getter methods, do you want it use the classes fields or the result of the - maybe override - getter method.

So, as usual, it depends, but I'd use getters unless I have a good reason to access the fields directly.

Problem

I've seen both approaches used but have never heard that one way is preferred over the other for any particular reason. ``` public String toString() { return this.field1 + " " + this.field2; } ``` versus ``` public String toString() { return getField1() + " " + getField2(); } ``` I used String concatenation in my example to keep the code brief.

Original source

Related problems