Search code examples
typesenumsbooleanenumerationstrong-typing

Should Left or Right be represented as a boolean or an enum


For any language that contains boolean and enumerations as primitive types which type should I use for variable that stores whether something is left or Right.

My initial instinct is to use an enumeration as it is much more descriptive - definitely a big plus for enumerations.

But it occurs to me that in a case where a value must be either Left or Right then a boolean would be both safer and more memory efficient - both points in favour or using a boolean.

There's also an issue in that a boolean value has a natural orientation but for a value like Left Right there is no natural mapping meaning you'd need to use the value something like this isLeft - a point against using a boolean.

Is there a convention or best practice for values like this which are both binary and exclusive but do not have any immediate symmetry to on/off, zero/one or any other natural boolean interpretations?


Solution

  • Context: I primarily work in C++

    I'd use an enumerator. I wouldn't know looking at somebody's project whether true meant left or right without checking the documentation, but with enumerators it's obviously. I'd also be worried about different parts of the code changing what that default was.

    You may be able to get around the changing default with constants (e.g., const bool left = true;), but that introduces other interesting options in the code (bool is_on = right;).