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.
- For expression && true, you can remove the && true.
- For expression || true, you can remove the entire expression and assume it is always true.
- For expression && false, you can remove the expression and the entire block, since it is not possible for it to ever be true.
- 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.


[...] A good example of this would be my post on refactoring the removal of conditions. [...]
By: Living Dangerously: Refactoring without a Safety Net « Making the Complex Simple on October 1, 2010
at 9:54 am