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.
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".
Now specifically, the objects in this system are graphic elements like rectangles, circles, etc and the current representation is to display x, y, scale, bounds, etc...
So, where does the crowd lie?
When should you and when shouldn't you implement toString?
If there is no implementation for toString() found in the class, then the Object class (which is a superclass) invokes toString() automatically. Hence, the Object. toString() gets called automatically.
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.
You can if you want to change the string representation of you object. The point in having a toString method in your abstract Animal class was probably exactly this: then you don't need to declare one in the child classes (or at least in some of your child classes you don't need).
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.
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.
Removing well-written (or even halfway decently written) toString() methods is pure insanity, IMO. Yes, I am often too lazy to write these (as often the objects don't end up having them used anyway), but they are extremely handy to have.
I really can't think of a good reason to want to get rid of these.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With