YesOrNo: useful idiom helper or wanking?

Dmitry Olshansky dmitry.olsh at gmail.com
Mon Apr 11 08:22:39 PDT 2011


On 11.04.2011 18: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.
>
>
Well, it's workaround but an interesting one.
I presume the user side remains intact and it's just enum declaration 
that got inculcated into the someFunction declaration, right? (I suspect 
some folks on the  NG might be puzzled by it so I'll try to clarify some 
points)
Like:
someFunction(...,SomeOption.yes,...);

Then yes it marks certain progress, and I like it. BTW double definition 
is also nicely solved (i.e. it would be the same template instance). 
YesOrNo!"Direction" would be the same for all function dealing with 
"Direction" parameter.

Then to save lives of novices reading API docs, we should have some nice 
short memo about this idiom on the language page or even in the Phobos 
module listing "common idioms" if we have lots of them, plus links to it 
everywhere applicable.

-- 
Dmitry Olshansky



More information about the Digitalmars-d mailing list