Chapter 71. Refactor Boolean Values to Enumerations
Peter Hilton
You wouldn’t use “magic numbers” in your code, so don’t use magic Booleans either! Boolean literals are worse than hardcoded numbers: a 42 in the code might look familiar, but false could be anything, and anything could be false.
When two variables are both true, you don’t know whether that’s a coincidence or whether they’re both “true” for the same reason and should change together. This makes the code harder to read, and causes bugs when you read it wrong. As with magic numbers, you should refactor to named constants.
Refactoring 42 to an ASCII_ASTERISK or EVERYTHING constant improves code readability, and so does refactoring true to a Boolean constant called AVAILABLE in a Product class, for example. However, you probably shouldn’t have any Boolean fields in your domain model: some Boolean values aren’t really Boolean.
Suppose your Product entity has a Boolean available field, to indicate whether the product is currently being sold. This isn’t really a Boolean: it’s an optional “available” value, which isn’t the same thing because “not available” really means something else, like “out of stock.”
When a type has two possible values, that’s a coincidence, and can change—by adding a “discontinued” option, for example. The existing Boolean field cannot accommodate the additional value.
Beware: using null to mean something ...