How to refactor simple boolean checks in if statements and avoid bad practices.

This is the first post out of a number of posts dealing with refactoring. This particular post is aimed at beginners, but further posts will contain somewhat more advanced concepts.

The concepts presented here can be used in a lot of programming languages, but the article is written with Java, PHP, and JavaScript in mind.

For one-liners, the general formating will look like this:

some expression => better expression doing the same thing

Check if a Value is True or False

if (A == true) => if (A) if (A == false) => if (!A)

This is something I see a lot of beginners do. It’s not the end of the world, but it does lead to harder to read code, possible bugs, and expresses a lack of deeper understanding.

Empty if-Statement

if(A) {
} else {
    // do the thing

This can be written a lot cleaner by negating the condition:

if(!A) {
    // do the thing

Check Multiple Values, Some of which are the Same

if ((A && B) || (A && C) || (A && D)) => if (A && (B || C || D))

This is possible because AND and OR are distributive.

Simplify Complex if Condition

If you are not that well versed with boolean logic, you should read up on negation and boolean algebra in general (especially de Morgan and distributivity).

Just a couple of examples of how complex if conditions can be simplified using boolean logic:

  • !(!A || !B || !C) => A && B && C
  • A && (A || B)) => A
  • (A || B) && (!A || C) && (B || C) => (A || B) && (!A || C)