“Beware Bags of Bools”

Monday, 1 May 2006

Derek Denny-Brown:

If you have ever had to maintain non-trivial code that uses a proliferation of flags to indicate the current state, you know what I mean. Does flag foo matter when flag bar is set? Or you fix a bug only to find that your fix breaks some esoteric case where the code can’t handle that particular combination of flags. Worse, each flag you add doubles the total “state-space”, i.e. the set of potential states that the code has to handle. Just 5 flags equates to 32 potential combinations. Are you testing every code path with all 32 potential combinations? I didn’t think so.

The solution? Store the majority of your state as an instance of an enum. […]

[…]

Do a favor for the future maintainer of your code. Don’t store your state as a grab-bag of bools.