YesOrNo: useful idiom helper or wanking?
FeepingCreature
default_357-line at yahoo.de
Mon Apr 11 08:16:09 PDT 2011
On 11.04.2011 16:53, Andrei Alexandrescu wrote:
> A fair amount of code in std uses this idiom:
>
> enum SomeOption { no, yes }
>
> void someFunction(...parms..., SomeOption, ...more_parms...) { ... }
>
> SomeOption is really a Boolean but replaces the unhelpful call syntax
> someFunction(...args..., false, ...more_args...) with the
> self-documenting ...args..., SomeOption,no, ...more_args...).
>
> The liabilities of using Booleans for describing flags have been
> documented in several places, including McConnell's Code Complete. I
> think the idiom above is a good replacement.
>
> One issue I have with it is that it requires separate definition and
> documentation. Usually the documentation awkwardly states "This type is
> really an option for someFunction, which you haven't seen yet. Skip this
> for now, then get back, and you'll understand." Moving the enum to after
> the function is possible but equally confusing.
>
> So I was thinking of planting a simple template in std.typecons:
>
> template YesOrNo(string name)
> {
> mixin("enum "~name~" : bool { no, yes }");
> }
>
> That way, the definition of the function needs no separately-defined is
> self-documenting:
>
> void someFunction(...parms..., YesOrNo!"SomeOption", ...) { ... }
>
> The question is to what extent this would mark progress and fostering
> structured use of this idiom, versus just confusing beginners and adding
> deadweight to Phobos.
>
>
>
> Andrei
Named parameters fix this without the need for workarounds.
someFunction(...parms..., someOption=>true, ...more parms....);
More information about the Digitalmars-d
mailing list