1

When writing a toString method in a Java class, should the field be used in the toString or should the class getter for that field be used? i.e:

private String name;

public NameClass(String name) {
    this.name = name;
}

public String getName() {
    return this.name;
}

public String toString() {
    return "This is the name:" + this.name;
}

// OR THIS
public String toString() {
    return "This is the name: " + getName();
}
  • 2
    Unless `getName()` is going to be more complicated or overridden, it doesn't matter – khelwood May 30 '18 at 14:22
  • 1
    This is mostly a matter of taste, I prefer this.name – ASF May 30 '18 at 14:23
  • in my opinion you can simply use the field `return "This is the name:" + name;` And for example autogenerated by IDEA toString() uses fileds, not getters – Danila Zharenkov May 30 '18 at 14:23
  • If you think about it, it's like wondering if you should use the field or the class getter to create... the class getter. Since it's in the class and you don't override it then it doesn't matter. If you want a full object oriented approache then use the class getter, but it doesn't matter – Hearner May 30 '18 at 14:24
  • 1
    Thanks! Tried searching for "getters in toString" etc. for a while but found nothing on SO. Seems I need to get better at searching. Thank you! – Edwin Carlsson May 30 '18 at 14:25
  • I've read both approaches to this. On one side you can assure that any logic that has to be done when anyone gets your attribute will be done if you always use your getters (not only in the toString method, but actually in every method of the class). On the other side some people argues that getters should only fetch the attribute, so that there is no unexpected behaviour. It'd be nice to read some experienced people on this matter. – Jorge.V May 30 '18 at 14:25
  • Also, I think unless you want to do something special in this "getName()" the code is more readable using "this.name" ... The reader will know that nothing was done especially on it. – Shani C May 30 '18 at 14:25
  • [My Google strategy for this question](https://www.google.com/search?q=java+tostring+call+getters+or+use+fields+site:stackoverflow.com) – Hovercraft Full Of Eels May 30 '18 at 14:27
  • @HovercraftFullOfEels look at that. That's brilliant. Thank you, mister MasterGoogler! – Edwin Carlsson May 30 '18 at 14:29

0 Answers0