logo

Improve bad code

Coding style quick improvement tip – IF statements

January 06, 2015

In my todays quick improvement tip for your coding style we’ll be focusing on the control structures, more accurately the IF statements.

BAD CODE

<?php
 
if($owedAmount>1000)
    send_email_to_client('owes_over_1000');

While there is nothing syntactically or semantically wrong with this code it is following bad practice and might provide a place for future bugs to hide. Let’s imagine we want to send an extra email to our billing department. With an inattentive programer, the inclusion of the required curly braces could be simply overlooked.

We could end up with a code like this. A nasty bug would find its new home and send false emails to our billing department.

BAD CODE

<?php
 
if($owedAmount>1000)
    send_email_to_client('owes_over_1000');
    send_email_to_billing('owes_over_1000');

Putting some care into our code when writing it, we can take care of such pitfalls and protect us or other programers from unintentionally creating bugs.

So let’s clear up this code so it reads better and is more solid. First we’ll add spaces to separate the language keywords from the parentheses and add curly braces to clearly define which part of the code, the control structure controls. While we’re at it, we will also add spaces around the logical operators to more clearly distinguish the parts of the logical expression.

GOOD CODE

<?php
 
if ($owedAmount > 1000) {
    send_email_to_client('owes_over_1000');
}

As you can see, the result is much easier to read and we removed the possibility of creating a bug when adding code to this control structure.

We have been following the PSR-2 Coding Style Guide for PHP.

These are the rules we followed:

  • Control structure keywords MUST have one space after them; method and function calls MUST NOT.
  • Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.
  • Opening parentheses for control structures MUST NOT have a space after them, and closing parentheses for control structures MUST NOT have a space before.

Code readability is a big part of good code and it is essential for any good programer to follow a coding style guide. The primary benefit is that other programers will read your code more easily. But it can also provide a few not so apparent improvements of the code quality, like removing places for bugs to hide as in our example.