Categories
Hard Skills Software Development

The correct way to write conditional expressions

(isItTrue == false) !== (false == isItTrue)

I have been programming for more than a decade, but it never occurred to me that there would be a good and a wrong way of writing a conditional expression. For example, if you write an if statement, would you think that it matters how you order a simple equality check as the one above?

Take a look at the following example.

Would you think there is a difference between

if (isItTrue == false)

and

if (false == isItTrue)

?

During my career, I never gave it a second thought until today as I was reading the WordPress coding standards page, and it turns out there is a good reason to choose one over the other.

As the WordPress coding standard page states, it is quite common to mistype the == and write a single equal sign instead = . Now, let’s say we made that typo in our code. Take a second look at those two statements again:

if (isItTrue = false)

and

if (false = isItTrue)

Would you say there is a difference between the two statements?

There is definitely a bug in both, but no matter what programming language you use, it will result in a hard-to-debug problem, depending on which style you are using. If you choose the correct version, you can rely on the interpreter/compiler to pinpoint the problem.

Before I give you the answer of which style should be followed

Let’s try to examine the result of the two statements.

First: if (isItTrue = false)

In that case, the isItTrue is a variable, and we are assigning a native boolean value to it. This action is doable; hence the if statement will get the value of false regardless of the initial value of the isItTrue variable. Because we used an assignment operator, and after that, we check the new value as soon as the assignment was done. The code compiles, and as a result, you will only see a runtime bug, that this if statement never will allow to run the code inside.

In comparison: if (false = isItTrue)

This statement will throw an error because, in the if statement, you are trying to assign the value of a variable into a constant/native value. As soon as you run this code, it will not run, but pinpoint you the problem that you try to use an assignment instead of an equality check.

Verdict

If you read it through, you probably already realized that the recommended way of writing a simple condition is to put constants/native values on the left of the comparison and the variables on the right, so if you would mistype it for an assignment operator, it would prompt you the problem as soon as you build/run the code.

By Botond Bertalan

I love programming and architecting code that solves real business problems and gives value for the end-user.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.