Interpolated strings
Nick Sabalausky (Abscissa) via Digitalmars-d
digitalmars-d at puremagic.com
Thu Apr 20 12:32:18 PDT 2017
On 04/20/2017 02:28 PM, Atila Neves wrote:
>
> I don't understand how
>
> writeln($"{a} times 3 is {a * 3}");
>
> is even marginally better than
>
> writeln(a, " times 3 is ", a * 3); // look ma, works right now!
>
> It's not even fewer characters.
>
> Atila
>
The latter IS pretty good, I use it often. It's *VASTLY* better than
format strings[1].
But, cognitively, I find the former much easier to read and write
(Apparently many other people seem to as well, although perhaps not
everyone). I'm not sure I can explain why especially well, but the
visual parsing is just much simpler and more symmetric, and it's much
easier to tell at a glance where the full, umm "string", starts and
ends, and what's going inside the string and what isn't.
[1] Format strings, even with the new compile-time improvements in the
latest DMD, for one thing, they still fail at DRY: Ie, with format
strings, even compile-time ones, you're listing your parameters TWICE -
once to describe WHERE they go and how they're formatted, and then again
SEPARATELY to select WHAT data to be rendered.
And then format strings also have the downside that the "WHAT data" is
specified out-of-band, making it making it easy to get things flipped
around, and just generally harder to see at-a-glance what's going on
(similar to how UFCS chains can be easier to read than a tree of nested
function calls, because for UFCS chains the ordering is perfectly
sequential, unlike nested function calls and format strings where the
logic jumps around).
TBH, I'm not all that excited about the compile-time enhancements to
format strings simply because...they're still format strings. And not
only that, but they're printf-style syntax which is a total unintuitive
mess (C#'s format string syntax was vastly better...for a format string,
anyway...)
IMO, the only time a format string should be used instead of
std.conv.text() or interpolated strings is when:
1. You're just rendering *one* value at a time with non-standard
formatting options (ie, left-/right-justified, leading/trailing zeroes,
etc). (Speaking of which, `interp` could really use some formatting
features so this could be avoided, and for performance reasons.)
2. You need to support custom formatting specified at runtime (ex:
software that supports displaying date/time in custom user-defined
formats) but want to be lazy about it and not bother finding/writing a
more user-friendly formatting syntax than printf-style (ie, extremely rare).
More information about the Digitalmars-d
mailing list