YesOrNo: useful idiom helper or wanking?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Apr 11 07:53:22 PDT 2011


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


More information about the Digitalmars-d mailing list