Friday, December 10, 2010

booleans Galore

Often I bump into code which contains convoluted logic involving a lot of booleans.

If the booleans are independent, then the number of states represented by the booleans is 2^n. All too often, however, the number of REAL states that the object can be in (based on those booleans) is much lower. That is because the booleans are interdependent and setting one to true may mean another one needs to be set to false, etc.

After 4-5 such interconnected booleans, the logic can get blurry, and code hard to read.

One thing that seems to help is to replace multiple booleans with one enum variable. The enum represents the true combined state of the object(s). Sometimes a state may correspond to one of the booleans being true, or sometimes it can be a combination. It's important to get an overview of what can happen to the object and which of the booleans are dependent on each other, and which are completely independent (and perhaps should not be included in this state machine). The number of entries in the enum will then represent the actual states of the object.

Now this one is very much on a case by case basis, but a few times I've managed to reduce logic from 4-5 interconnected booleans (16-32 states) to 5-10 enum entries, which gets MUCH easier to reason about.

Anything else? Hmm... I think that's all I'm gonna say today. Refactoring awaits. MWAHAHAHA

No comments:

Post a Comment