DIP9 -- Redo toString API

Bruno Medeiros brunodomedeiros+spam at com.gmail
Thu Dec 2 08:31:49 PST 2010


On 21/11/2010 17:21, Don wrote:
> spir wrote:
>> On Sun, 21 Nov 2010 03:17:57 -0800
>> Jonathan M Davis <jmdavisProg at gmx.com> wrote:
>>
>>> You're not losing _anything_ out of the deal except that you wouldn't
>>> do obj.toString(). Instead you'd do to!string(obj).
>>
>> I'm usually not using toString(), it's supported by the language. What
>> about format("%s:%s", a,b)? Will it still call toString implicitely,
>> or writeTo a buffer, or what else?
>>
>> Anyway, I cannot see any advantage in deprecating toString() for every
>> programmer in every use case, just for hypothetical efficiency issues
>
> The efficiency issues are important, but are not the primary motivation.
> toString() is just wrong. The idea that there is ONE AND ONLY ONE
> textual representation of an object, is, frankly, idiotic.
>
>

That idea is quite idiotic indeed, no question about it. However, that 
is not toString() 's idea! The point of toString (at least across 
languages, not D specifically) is to provide a *default* representation 
of a type.

It doesn't preclude other representations, and if format&friends 
(writef, etc.), don't provide an integrated way to create/write a string 
using custom formats for a given object/struct, that is format's 
problem, it is not toString's fault.

One might ask, well, is toString any use then? Yes, very much, the idea 
to provide a *default* representation of an object/struct is quite 
useful. There are many situations where one would want to print a string 
of an object without specifying any particular format. In fact, there 
are some situations where specifying a particular format would not even 
be possible or make sense, for example, when the code doesn't know the 
exact type of the underlying object/struct (and thus not know what 
formats are supported). Like a container printing its elements. Another 
example I take from Java, it doesn't apply that much to D (at least not 
at the moment), but still I want to point it out: toString() is used 
extensively by the integrated debugger in JDT to print representations 
of objects in views, popups, etc..

In fact, I think that coding only a default toString for a type may be 
more common than otherwise (coding a toString that actually uses the 
format specifiers). The string based format specifier is just not that 
common outside of numerical types.

The question remains, if toString should support a format specifier or 
not. I think it shouldn't, if there is an alternative satisfactorily 
solution for numerical types and format&friends.

-- 
Bruno Medeiros - Software Engineer


More information about the Digitalmars-d mailing list