Coding Tip #27: turning bools into enums
On my recent project, I have noticed a resurgence in a pattern that I have seen many times previously: where a field which is represented as a boolean needs to evolve to represent more than just two values (true and false). The number of times that I have encounted this makes me believe that you should always start with enum, regardless if the values are True and False, just to make your life easier down the line.
As much as refactoring tools like resharper help you out, when it comes to refactoring a bool into an enum, it’s a pain in the arm. One of these pain points being that quite often, you see:
if (fieldRepresentedByBool) {}
which makes it quite annoying to turn it into:
if (fieldNowRepresentedByEnum.Equals(Enum.True))
Another pain point is refactoring your database is not much fun, especially if you have to ensure that you also migrate data.
The other benefit that you get from enums when compared to booleans is that your method signatures are more expressive. Consider these two signatures (yes, I know completely contrived, but I couldn’t think of a better example), and tell me which one you prefer.
render(foo, true) // where true represents isVisible
render(foo, Display.Visible)
So, next time you start to type bool think about using an enum instead.
Posted: May 25th, 2009 under Design.
Comments
Comment from John Nolan
Time May 29, 2009 at 4:41 pm
This article reminds me of the famous
enum Bool
{
True,
False,
FileNotFound
};
Pingback from Sarah Taraporewalla’s Technical Ramblings » Coding Tip #42: turning enums into classes
Time June 29, 2009 at 6:24 am
[...] Coding Tip #27 I explained how I rarely like to use booleans to represent states, and prefer to use an enum. Now [...]
Comment from Morten Lyhr
Time May 27, 2009 at 1:09 pm
Or make it really readable:
render(foo);
renderVisible(foo)