logo

Improve bad code

Conditional statement the safe way

June 15, 2015

This post will be really short. No big story behind it, just a simple habit that you should practice to give the quality of your code a level up.

Conditional statements seem easy and there should be no real complexity behind them. On the other hand how many times a simple mistake like this happened to you?

BAD CODE

<?php
 
if ($payment = 100) {
    // do something here
}
else {
    // do something else here
}

Did you catch the issue in the conditional statement above? This sort of thing happens a lot, regardless if you’re a novice developer or a software architect ninja. Using an assignment operator (=) instead of a comparison operator (==) can lead to unexpected behavior from overwriting a variable. However, there is a simple trick, to catch these errors before they turn your day into a sad bug hunting trip.

GOOD CODE

<?php
 
if (100 == $payment) {
    // do something here
}
else {
    // do something else here
}

The easy trick to getting your conditional expressions safe is to turn them around. In this case, if we would make the mistake of using an assignment (=) instead of a comparison (==), since you can’t assign values to constants. Such errors are then caught early on, before they make it into some part of your code, that is later behaving strangely.

Hope you find this short tip useful, please share your ideas in the comments below.