By January 18, 2010

How to Refactor Removal of Conditions

One common problem I have been seeing, which can lead to some nasty errors, is the removal of conditions which no longer can be true.  In the application I am working on we frequently have the need to remove code which can no longer be set.  Often when this is done errors can be introduced.  I thought I would share with you my technique to refactor this kind of code in a way that makes it easy to prevent logical errors coming into place.

Here is some example code:

Step 1: Set the condition to remove to false, since it can never be set to true.

Step 2: Simplify (In this case !false = true)

Step 3: Remove or change expression, (in this case && true never can affect the expression, so we can just remove it completely)

This is a very simple example, but for more complicated scenarios, this technique can help you avoid simple mistakes.
Here are some general rules when you refactor boolean expressions.

  1. For expression && true, you can remove the && true.
  2. For expression || true, you can remove the entire expression and assume it is always true.
  3. For expression && false, you can remove the expression and the entire block, since it is not possible for it to ever be true.
  4. For expression || false, you can remove the || false, since this will never affect the expression.

It seems like a basic thing, but you would be surprised how often removing code in boolean expressions is done incorrectly. I have made the mistake myself. For that reason I always follow this simple process.

About the author

John Sonmez

John Sonmez is the founder of Simple Programmer and a life coach for software developers. He is the best selling author of the book "Soft Skills: The Software Developer's Life Manual."