YesOrNo: useful idiom helper or wanking?
Nick Sabalausky
a at a.a
Mon Apr 11 12:35:22 PDT 2011
"Andrei Alexandrescu" <SeeWebsiteForEmail at erdani.org> wrote in message
news:inv4rv$1dfl$1 at digitalmars.com...
>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.
>
Named args are much better for this. No boilerplate needed. Of course,
without named args, yea, this idiom needs to be used.
> 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.
>
/// Documentation here
enum SomeOption { no, yes }
///ditto
void someFunction(...parms..., SomeOption, ...more_parms...) { ... }
That groups the two together, right? So solved.
> 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.
>
Not sure what I think, really. Although, I do think the fact there seems to
be a need for someting that complex just for a mere two-option setting is
more indication that named args are just a better approach. But since we're
stuck without that, I really don't know how I feel about this template. Umm,
if you need to add a third setting, then you're right back to using a
straight enum and making sure it's documentated sensibly. You could
generalize YesOrNo further, but I don't think's possible without making it
really ugly to use. So maybe it's better to just make sure there's a good
way to handle the documentation. If that turns out to require some new DDoc
feature, then so be it.
More information about the Digitalmars-d
mailing list