In programming, Booleans and Enumerates are common data types to represent the concept of “choice”.
When there are several things to choose from, the Enumerate is the only one to support it, so that’s clear.
But what about when you have two things to choose from? There might be some confusion between both data types since either of them supports handling binary choices.
The confusion arrises in particular when you want to add the choice of a new behaviour, on top of an existing one. For example:
We’re torn between adding a
boolean
calledsupportsBarMode
or having a more descriptive model with anenum
that lists all the supported options[FooMode, BarMode]
.The
enum
solution feels a bit YAGNI at the moment, but we’re open to suggestions. What do you think?
Don’t tie yourself to whether you’ll need more options in the future or not. Instead, look at how you can communicate intent the best way possible.
The mental model for encoding these binary choices is to identify which of these scenarios we are in:
- Switch something on/off — e.g. enabling or disabling an extra option
- Select mode of operation — e.g. choosing between ways of doing things
Boolean = Switch something on/off
A Boolean fits the 1st scenario. A light switch is either on (have light) or off (don’t have light). When it’s off, there’s no “default alternative behaviour” associated with it: the thing we want to turn on just isn’t there.
Enumerate = Select mode of operation
An Enumerate fits the 2nd scenario. A coaxial selector is either on position A or on position B. It lets you choose between two options. There is a clear meaning associated with each position.
In the example above, the Enumerate data type would be the right choice.
… an
enum
that lists all the supported options[FooMode, BarMode]
Even if we never add other options to that Enumerate, it is not a case of YAGNI. The Enumerate could have only 2 options forever that it would still communicate the correct intent.