Logo

Blog


A strongly typed bool

Today I like to share a pattern I have used for some time. The pattern is generally well-received whenever I present it during one of my training courses. I still don't know whether it is a use or abuse of a class enum, but you can decide for yourself.

Existing solutions

Let me first say there are a lot of good strong type libraries out there:

They aim at something much bigger than what I will show you here.

A simple solution for a special case

Suppose we have the following code fragment:

1
2
3
4
5
6
7
8
void FileAccess(bool open, bool close, bool readonly);

// ...

void SomeFunction()
{
  FileAccess(true, false, false);
}

Nothing prevents you or one of your colleagues from accidentally switching the first two parameters. Some coding guidelines recommend in such a case to put the parameter name as a comment in the function call like this:

1
2
3
4
void SomeFunction()
{
  FileAccess(/*open*/ true, /*close*/ false, /*readonly*/ false);
}

Ok, it is at least something. But, the compiler does not care for comments, nor do refactoring tools. Here is my way, which addresses only this case with a bool. If you need more strong data types, you should probably refer to one of the libraries mentioned above.

1
2
3
4
5
6
#define STRONG_BOOL(name)                                                 \
  enum class name : bool                                                  \
  {                                                                       \
    No  = false,                                                          \
    Yes = true                                                            \
  }

This makes a dedicated class enum which is based on a bool. Our code now looks like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
STRONG_BOOL(Open);
STRONG_BOOL(Close);
STRONG_BOOL(ReadOnly);

void FileAccess(Open open, Close close, ReadOnly readonly);

// ...

void SomeFunction()
{
  FileAccess(Open::Yes, Close::No, ReadOnly::No);
}

With that, switching two of these parameters is no longer possible. Plus, it is pretty well documented already. No additional comment is needed. Of course, whether you prefer Yes and No or True and False or something else is a matter of taste.

My conclusion

I think STRONG_BOOL is interesting because compared to the libraries above, STRONG_BOOL is more or less a single-line thing. You don't need to check the license of the library. You don't need to check how to build or integrate it.

Andreas