Simplifying conversion and formatting code in Phobos
Andrei Alexandrescu via Digitalmars-d
digitalmars-d at puremagic.com
Tue Sep 6 03:04:06 PDT 2016
We've learned a lot about good D idioms since std.conv was initiated.
And of course it was always the case that writing libraries is quite
different from writing code to be used within one sole application.
Consider:
* to!T(x) must work for virtually all types T and typeof(x) that are
sensible. The natural way of doing so is to have several
semi-specialized overloads.
* Along the way it makes sense to delegate work from the user-level
convenient syntax to a more explicit but less convenient syntax. Hence
the necessity of toImpl.
* The need to "please format all arguments as a string" was a natural
necessity e.g. as a second argument to assert or enforce. Hence the
necessity of text(x, y, z) as the concatenation of to!string(x),
to!string(y), and to!string(z).
* FormattedWrite was necessary for fwriteln and related.
* All of these have similarities and distinctions so they may use one
another opportunistically. The alternative is to write the same code in
different parts for the sake of artificially separating things that in
fact are related.
The drawback of this is taking this in as a reader and maintainer. We
have the 'text' template which calls the 'textImpl' template which calls
the 'to' template which calls the 'toImpl' template which calls the
'parse' template which calls the 'FormattedWrite' template which calls
the 'to' template. Not easy to find where the work is ultimately done.
It is a challenge to find the right balance among everything. But I'm
sure we can do better than what we have now because of the experience
we've gained.
If anyone would like to take a fresh look at simplifying the code
involved, it would be quite interesting. The metrics here are simpler
code, fewer names, simpler documentation (both internal and external),
and less code.
Andrei
More information about the Digitalmars-d
mailing list