Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it desired to not implement toString() in Java?

Tags:

java

tostring

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?

like image 245
Allain Lalonde Avatar asked Jul 21 '09 19:07

Allain Lalonde


People also ask

What happens when there is no toString method in Java?

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.

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.

Is toString required for all classes in Java?

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).

Why do we need toString in Java?

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.


2 Answers

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.

like image 188
djna Avatar answered Sep 20 '22 11:09

djna


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.

like image 42
jsight Avatar answered Sep 19 '22 11:09

jsight