Why does toString() exist? It seems useless.

Don nospam at nospam.com.au
Mon Aug 18 06:15:51 PDT 2008


bearophile wrote:
> Don Wrote:
>> I cannot understand the rationale for a toString() member function which 
>> doesn't support formatting.
> 
> I think the rationale is that it's a simple function that performs a simple thing with an easy to use and easy to learn syntax, I have found it useful often.

I think it encourages a very bad programming style. It makes ONE case 
very easy, but does nothing for the other cases. It doesn't scale at all.

> For more complex purposes you can write your own printing methods, 

> or you can write a method that changes the printing state of the class/struct, 
 > that is later read and used when you call toString() and used to 
change its behavior.

But the way it is formatted should be a property of the output stream, I 
think, not a property of the object. Certainly this is the way C and C++ 
  I/O works.

> 
> So I have created a graph class that by default when you call toString() gives a compact and simple textual representation of the graph. 
Then there are other methods, one that returns a string that shows the 
matrix of links, another that shows the weights of the arcs too, etc.

  There is also the possibility to modify the printing defaults with 
another method, to then later toString() acts differently.

Then I got suspicious that this might have come from Java or .NET.
I googled for toString in Java and found:
---
http://www.javapractices.com/topic/TopicAction.do?Id=55
---
"The toString method is widely implemented. It provides a simple, 
convenient mechanism for debugging classes during development. It is 
also widely used for logging, and for passing informative error messages 
to Exception constructors and assertions. When used in these informal 
ways, the exact format of toString is not part of the contract of the 
method, and callers should not rely on the exact format of the returned 
String."
---
Now this makes sense. It's a useful hack. If it's just for debugging and 
error messages, that's fine. But if that is what it's for, the normal 
runtime I/O should discourage its use elsewhere (eg, by appending the 
class name in front).

OTOH if it is intended for general I/O, I think it's a horribly broken 
design.


More information about the Digitalmars-d-learn mailing list