Skip to content

Commit

Permalink
Document new idiom for using Flag.
Browse files Browse the repository at this point in the history
  • Loading branch information
H. S. Teoh committed Nov 19, 2014
1 parent f5a53ad commit 512b0ab
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions std/typecons.d
Expand Up @@ -5183,33 +5183,37 @@ bool) makes the flag's meaning visible in calls. Each yes/no flag has
its own type, which makes confusions and mix-ups impossible.
Example:
Code calling $(D getLine) (usually far away from its definition) can't be
understood without looking at the documentation, even by users familiar with
the API:
----
// Before
string getLine(bool keepTerminator)
{
...
if (keepTerminator) ...
...
}
...
// Code calling getLine (usually far away from its definition) can't
// be understood without looking at the documentation, even by users
// familiar with the API. Assuming the reverse meaning
// (i.e. "ignoreTerminator") and inserting the wrong code compiles and
// runs with erroneous results.
auto line = getLine(false);
----
Assuming the reverse meaning (i.e. "ignoreTerminator") and inserting the wrong
code compiles and runs with erroneous results.
After replacing the boolean parameter with an instantiation of $(D Flag), code
calling $(D getLine) can be easily read and understood even by people not
fluent with the API:
// After
string getLine(Flag!"KeepTerminator" keepTerminator)
----
string getLine(Flag!"keepTerminator" keepTerminator)
{
...
if (keepTerminator) ...
...
}
...
// Code calling getLine can be easily read and understood even by
// people not fluent with the API.
auto line = getLine(Flag!"KeepTerminator".yes);
auto line = getLine(Flag!"keepTerminator".yes);
----
Passing categorical data by means of unstructured $(D bool)
Expand All @@ -5219,9 +5223,19 @@ kinds of coupling. The author argues citing several studies that
coupling has a negative effect on code quality. $(D Flag) offers a
simple structuring method for passing yes/no flags to APIs.
As a perk, the flag's name may be any string and as such can include
characters not normally allowed in identifiers, such as
spaces and dashes.
An alias can be used to reduce the verbosity of the flag's type:
----
alias KeepTerminator = Flag!"keepTerminator";
string getline(KeepTerminator keepTerminator)
{
...
if (keepTerminator) ...
...
}
...
// Code calling getLine can now refer to flag values using the shorter name:
auto line = getLine(KeepTerminator.yes);
----
*/
template Flag(string name) {
///
Expand Down

0 comments on commit 512b0ab

Please sign in to comment.