A lead developer on my project has taken to referring to the project\'s toString() implementations as \"pure cruft\" and is looking to remove them from the code base.
<What harm do they do? Why remove them if you have them? I find toString() extremely useful when emitting debugging statements.
Personally, I would always err on the side of having a workable toString() method. So little work to write.
It is good for debugging purposes. But if you want to display given object as a string to the end user you should never use toString() implementation but provide custom method for that.
So regarding
I've said that doing so would mean that any clients wishing to display the objects would have to write their own code to convert the object to string, but that was answered with "yes they would".
I agree with your team lead. If you want to display object to any client use custom implementation. If you want to use it for debugging purposes use toString().
Well, he does stramge thing.
I can not say toString() is too useful. For presentation you will need other tools.
But toString() is quite useful for debugging, because you could see the contents of collections.
I do not understand why remove it if it is written already
I would definitely keep the toString() implementations, particularly for debugging purposes. As a primarily C++ developer, I wish things were as easy in C++ as they are in Java in this respect (operator overloading can be a pain).
I figured I'd weigh in with a more modern perspective given that this question is now almost 10 years old.
toString
is obviously helpful for debugging - you need look no further than all of the other answers here which attest to that - but debugging information isn't business logic.
Having a toString
method in every single class is visual clutter which obscures the useful behaviour of the class. We also need to remember to maintain it - either manually or by regenerating the method from our IDE - every time we change the class fields.
So what can we do to address these problems without removing the method altogether? The answer is to automatically generate it. Project Lombok's @ToString annotation can automatically generate a toString
method for you at compile-time which includes any combination of fields that you choose.
Basic sample usage:
@ToString
public class Foo {
private int i = 0;
}
Which will become equivalent to the following at compile-time:
public class Foo {
private int i = 0;
public String toString() {
return "Foo(i=" + this.i + ")";
}
}
I've always made sure that my classes implemented toString.
It provides a simple way of debugging the current state of the class when I'm debugging and when I'm logging errors, I can include it into my log messages.