Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is toString() only useful for debugging?

Tags:

java

c#

tostring

Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.


EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

like image 298
Camilo Díaz Repka Avatar asked Feb 19 '09 01:02

Camilo Díaz Repka


2 Answers

No, the key is that you're supposed to override the default implementation of ToString() to make it useful. ToString() can be a great way to output the value of something back to the UI.

A simple example would be if you have a Name class with a three strings (First, Middle, Last). You can have a ToString() method that formats it for the UI: "Last, First Middle" for example.

Or a class that stores a mathematical operation (values Left=2, Right=3, Result=6 and an operator enum=Multiply). Call ToString() to get "2 * 3 = 6".

However, it is probably more common to have a variety of different To<qualifier>String() methods, like the .NET DateTime class. (ToShortDateString(), ToLongDateString(), ToLongTimeString(), ...)

Edit: As for why it's rooted at the Object class, it's simply because ToString() is a valid operation for anything.

Additionally, strings can be a good way of marshaling between data types or data consumers, because it's (practically) guaranteed to be parsable and doesn't require extra encoding or care.

like image 158
lc. Avatar answered Oct 19 '22 23:10

lc.


My personal preference is that toString() should never be used for anything other than debugging. If you want to produce a string for an object, provide a separate method that clearly documents your intent (getName(), getDescription(), etc). Never rely on the implementation of a toString().

The problem is that many developers see toString() as a debug-level string and think nothing of changing it (say when new fields are added or removed). Heck, some automated toString() builders use reflection to generate a toString() from the fields.

I've found this preference has served me well over the years.

like image 21
Alex Miller Avatar answered Oct 20 '22 00:10

Alex Miller