Another idiom I wish were gone from phobos/druntime

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Thu Feb 5 00:00:55 PST 2015


On Wednesday, February 04, 2015 16:24:14 Andrei Alexandrescu via Digitalmars-d wrote:
> I'm seeing another idiom that seems to become fashionable. Consider this
> excerpt from
> https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L407:
>
>              auto opSlice(size_t low, size_t high)
>              in
>              {
>                  assert(low <= high);
>              }
>              body
>              {
>                  import std.range : take;
>                  return this[low .. $].take(high - low);
>              }
>
> which of course trivially boils down to:
>
>              auto opSlice(size_t low, size_t high)
>              {
>                  assert(low <= high);
>                  import std.range : take;
>                  return this[low .. $].take(high - low);
>              }
>
> What advantage could possibly be in transforming a 5-liner into a
> 9-liner? Are we really aiming at writing the maximum possible lines of
> code here and using as many language features as possible everywhere?
>
> I think we should dust off that Phobos contributors' guide. Sadly, there
> is little we can do against the more subtle issues.

As far as I can tell, there is zero reason to use in blocks aside from with
classes, since with virtual functions, inheritance comes into play, and the
semantics aren't the same. But for the vast majority of functions, I totally
agree that using an in block is just visual noise.

Similarly, I think that out blocks are pretty useless. They're of some value
when you have multiple return statements and want to check something when
the function exits, but in the vast majority of cases, what you're testing
with an out contract is what unit tests would be testing, in which case, the
out blocks don't really add anything, and since they're forced to be
general, you can't test for specific results like you can with a unit test.
Sometimes, testing something in the out block can be useful, but in my
experience, unit tests almost always take care of it.  So, in most cases,
out contract blocks don't really add anything IMHO and are pretty pointless
(though the exception of virtual functions applies in this case as well).

So, while I totally agree that contract programming is valuable, I don't
think that the special syntax that D provides for it is of much value except
in the case of virtual functions. And the fact that that syntax is so noisy
(especially when there's only one assertion) makes it kind of ridiculous
IMHO to use in blocks or out blocks on non-virtual functions.

- Jonathan M Davis



More information about the Digitalmars-d mailing list