Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

tostring

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.

like image 387
Aaron Avatar asked Jan 15 '10 16:01

Aaron


People also ask

Should toString use getters?

Using getters in toString is an overkill. And you should not be using toString for non debug purposes. Save this answer.

Should getter methods be public or private?

In general, they should be public. If they are private they can only be called from within your class and, since you already have access to the private variables within your class, are redundant. The point of them is to allow access to these variables to other, outside, objects. Save this answer.

Why should you override the toString () method?

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.

What will happen if we don override toString () method?

There will not be enough information about state or properties of object. So, whenever you use or print a reference variable of type in which toString() method is not overrided, you will get an output like above. You will not get what the object actually has in it.


2 Answers

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.

like image 137
Andreas Dolk Avatar answered Oct 27 '22 01:10

Andreas Dolk


Using accessor methods might be preferred if they provide any additional logic on top of just returning the field's value (like uppercasing a string, or something like that). If your class is designed to be extended, I would tend towards accessors because they may be overridden.

like image 33
danben Avatar answered Oct 27 '22 00:10

danben