Semantics of toString

Justin Johansson no at spam.com
Sun Nov 8 19:46:32 PST 2009


Lutger Wrote:

> Justin Johansson wrote:
> 
> > I assert that the semantics of "toString" or similarly named/purposed
> > methods/functions in many PL's (including and not limited to D) is
> > ill-defined.
> > 
> > To put this statement into perspective, I would be most appreciative of D
> > NG readers responding with their own idea(s) of what the semantics of
> > "toString" are (or should be) in a language agnostic ideology.
> > 
> 
> My other reply didn't take the language agnostic into account, sorry. 
> 
> Semantics of toString would depend on the object, I would think there are 
> three general types of objects:
> 
> 1. objects with only one sensible or one clear default string 
> representations, like integers. Maybe even none of these exist (except 
> strings themselves?) 
> 
> 2. objects that, given some formatting options or locale have a clear string 
> representation. floating points, dates, curreny and the like. 
> 
> 3. objects that have no sensible default representation.
> 
> toString() would not make sense for 3) type objects and only for 2) type 
> objects as part of a formatting / localization package. 
> 
> toString() as a debugging aid sometimes doubles as a formatter for 1) and 2) 
> class objects, but that may be more confusing than it's worth. 
> 

Thanks for that Lutger.

Do you think it would make better sense if programming languages/their libraries
separated functions/methods which are currently loosely purposed as "toString"
into methods which are more specific to the types you suggest (leaving only
the types/classifications and number thereof to argue about)?

In my own D project, I've introduced a toDebugString method and left toString alone.
There are times when I like D's default toString printing out the name of the object
class.  For debug purposes there are times also when I like to see a string printed
out in quotes so you can tell the difference between "123" and 123.  Then again,
and since I'm working on a scripting language, sometimes I like to see debug 
output distinguish between different numeric types.

Anyway going by the replies on this topic, looks like most people view toString
as being good for debug purposes and that about it.

Cheers
Justin






More information about the Digitalmars-d mailing list