logo

Improve bad code

Conditional statement the readable way

June 03, 2015

Conditional statements and conditional expressions are a good way to branch our computational or business logic. Sometimes we as developers can be tempted to combine multiple conditional expressions in one long worm-like expression that is hard to understand, let alone test. Such cases should either be avoided or follow a coding style guide, which would at the very least improve the readability of a combined expression.

Readability wise, long combined conditional expressions can be extracted into a method, which can have a nice descriptive name.

GOOD CODE

<?php
 
if ($this->positiveBalance($account)) {
    // do something here
}
else {
    // do something else here
}

Reading this conditional it is immediately clear what it is checking. The actual conditional expression can be more complex, but that is no reason to decrease the readability of the code. Here’s an example of a badly written conditional expression, which is following a coding style guide for readability, but is stil hard to comprehend.

BAD CODE

<?php
 
if (
       ($account['balance'] > 0
        && $account['status'] == 'active')
       || ($account['hasLimit'] == true
           && $account['balance'] > $account['limit'])) {
    // do something here
}
else {
    // do something else here
}