Why does toString() exist? It seems useless.

Fawzi Mohamed fmohamed at mac.com
Wed Aug 20 13:38:33 PDT 2008


On 2008-08-18 16:28:36 +0200, "Steven Schveighoffer" 
<schveiguy at yahoo.com> said:

> "Don" wrote
>> I cannot understand the rationale for a toString() member function which
>> doesn't support formatting.
>> [...]
> As you have discovered, it is for simple debugging.

yes

> However, it's not even close to as useful as Java, where if you combine a
> string with an object, it automatically calls the toString function.
> 
> As far as supporting an output method, I think toString is completely the
> wrong way to look at it.  A simple example is a container class, such as a
> vector of ints.
> 
> Let's say you are outputting a vector of ints every time it has changed.
> What ends up happening is you build a (possibly huge) string every time you
> output the vector, and then are throwing the string away!  When all you
> really need is about 20 bytes of stack space to create the individual int
> strings and then output to an i/o function.
> 
> Even with a format string, that doesn't solve this problem.
> 
> What I would like to see is an output method in Object that looks like:
> 
> int output(int delegate(char[] x) sink, char[] fmt = null);

I fully agree I normally write a method that writes to a stream, with 
handles to tailor the output.
I also often write a desc method that gives a detailed description of 
all the variables of the object.

Then I write toString that calls one of these methods with some default 
arguments on a special stream the creates a string.
In general stream based output is much superior to conversion to a 
string (more efficient and often simpler to write), and when needed one 
can use a special stream that returns a string.

In tango I use a Print!(T) instance as nice to use stream, nicer than a 
sink delegate.
I wrote a Stringify class that like Python StringIO returns the 
collected string upon request.

> And something like how 'toString' works in a struct (where there is an
> xoutput function in the struct typeinfo class).

yes would also be nice to have

> This is a generic solution, it would be customized to the appropriate i/o
> library of Tango or Phobos.  Possibly the format strings would be different
> based on the I/O (i.e. Phobos uses printf style formatting constructs, Tango
> uses .NET style).

I am not too sure that I want to always have a format string, encoding 
and decoding it might be tedious, normally having a method with extra 
arguments is better.

Serialization is another topic, there the format should be defined by 
the stream.

Fawzi



More information about the Digitalmars-d-learn mailing list