Advertisements
Posted by: jsonmez | 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 a 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 for refactoring this kind of code in a way that makes it easy to prevent logical errors coming into place.

Here is some example code:

  if ((firstCondition || secondCondition) && !conditionToRemove)
  {
            // do something
  }

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

  if ((firstCondition || secondCondition) && !false)
  {
            // do something
  }

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

  if ((firstCondition || secondCondition) && true)
  {
            // do something
  }

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

  if (firstCondition || secondCondition)
  {
            // do something
  }

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.

Advertisements

Responses

  1. […] A good example of this would be my post on refactoring the removal of conditions. […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: