Enums instead of booleans
Using enums instead of booleans where appropriate can bring a lot of clarity to your code.
For example, say you had an access control implemented as follows:
Sure, you can call methods to determine if the access is public or private. But, for one thing, it’s not very extensible. If you wanted to add another access level, such as “private to group”, the code becomes much more complex.
In any case, though, the code can be made clearer by using an enum:
Now, you can use conditional logic like:
It’s very clear which access level your logic is working with, and it’s easy to extend to more enums if necessary.
Specify your units!
When working with variables that reference quantities, it’s extremely important to specify your units. Otherwise someone maintaining your code later (probably you!) won’t be able to distinguish if you were referring to grams, dollars, feet, miles, milliseconds, seconds, or farthings. This can lead to very real problems; In 1999, NASA lost a $125 million Mars probe because the programmers didn’t take into account unit conversions.
So, if you’re working with time, for example, instead of using
specify the units, such as
Never rely on enum ordinal values
When working with enums, be very explicit about their values. Never rely on their order to derive meaning.
For example, instead of using
and relying on the order of those enums to derive their values, be explicit about their values, like this
This reduces brittleness. Code that relies on the order of the enums won’t break if they are reordered. Additionally, more enums can be added with out worrying about their order.
For more, see this discussion on StackOverflow: Is enum order sensitivity an antipattern?.