Refactoring Boolean Conditions Into Methods

Written By John Sonmez

Some people really, really don't like to refactor boolean conditions into private methods.  One time someone told me that if they ever saw code like:

They would find me and kill me. I wonder if Bob Martin gets lots of death threats, because he advocates this practice in his book “Clean Code: A Handbook of Agile Software Craftsmanship“, which I am presently reading.

I've been doing this kind of refactoring ever since I read “Code Complete: A Practical Handbook of Software Construction“.  (By the way every time I mention this book, I feel obligated to tell you that if you have not read this book, go read it now.  Seriously.  Buy this book and read it.)

Now, the example I show above is a little “simple”, but it is still easier to read than leaving the ProgramCode == “Special Code” in the main method.  (Forget that “Special Code” should be a constant for now.)

Let's look at a less trivial example:

In this example it is much more unclear what the logic is trying to do.  When you are reading this code you have to mentally figure out what all these boolean statements are actually testing.

Tell me… Is this easier to understand?

If you think the first example is easier to understand, you're much smarter than I am, because I just can't wrap the first set of boolean conditions around my head, (and I wrote them).  It may seem silly to write little one line methods, but the value is in abstraction.  These one line methods make it much easier to understand what the code is doing, and allow you to choose your level of “zoom” into the logic.

  • You can choose not to care about how the cat decides to eat and just look at it from the level of if the cat decides to eat, then he eats.
  • Or you can look at it from the level of how does this cat decide to eat.
  • Or you can zoom down one more and look at the what kind of food does that cat like level.


Writing good code is about making code easy to read and understand, not about making it compact.

What do you think?  Do you agree with refactoring boolean conditions?