Semantics of toString

Yigal Chripun yigal100 at gmail.com
Fri Nov 6 01:33:03 PST 2009


On 06/11/2009 07:34, Don wrote:
> Nick Sabalausky wrote:
>> "Don" <nospam at nospam.com> wrote in message
>> news:hcvf9l$91i$1 at digitalmars.com...
>>> Justin Johansson wrote:
>>>> So what does "toString" mean to you?
>>> It's a hack from the early days of D. Should be unavailable unless
>>> the -debug flag is set, to discourage people from using it. I hate it.
>>>
>>
>> What don't you like about it?
>>
>
> It cannot even do the most basic stuff.
> (1) You can't even make a struct that behaves like an int.
>
> struct MyInt
> {
> int z;
> string toString() { .... }
> }
>
> void main()
> {
> int a = 400;
> MyInt b = 400;
> writefln("%05d %05d", a, b);
> writefln("%x %x", a, b);
> }
>
> (2) It doesn't behave like a stream. Suppose you have XmlDoc.toString()
> You can't emit the doc, piece by piece. You have to create the ENTIRE
> string in one go!
>
>

The first issue you raise is IMO a problem with writefln and not with 
toString since writefln doesn't handle user-defined types properly.

I think that writefln (btw, horrible name) should only deal with strings 
and their formatting and all other types need to provide an (optionally 
formatted) string.
a numeric type would provide formatting of properties like number of 
decimal places, thousands separator, etc while user defined 
specification type could provide a type of standard format.

auto spec = new Specification(HTML);
string ansi = spec.toString(Specification.ANSI);
string iso = spec.toString(Specification.ISO);
writefln ("{1} {0}", ansi, iso); // i'm using the tango/C# formatting

the c style format string that specifies types is a horrible horrible 
thing and should be removed.

regarding the second issue:
forech (node; XmlDoc.preOrder()) writfln("{0}", node.toString());



More information about the Digitalmars-d mailing list