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.
- 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.