Code Perfectionist - Part 1 - Spacing

In recent months, I have found myself having a bit of a perfectionist when it comes to writing code in terms of the way it is formatted.

I don't claim that my way is the perfect way but some of these are basic PSR standard things and some are a few pet peeves that have.

This week is all about spaces!

PHP, like a lot of other languages, use brackets and semicolons to signify code blocks and end of lines. This means that spaces are completely meaningless in the context of code syntax. But there is nothing more beautiful (and readable) than 500 lines of perfectly indented code, perfectly spaced code.

Let's begin simple.

1) Breathing space

Please do not type:


Give that condition a little breathing space, you don't like it when people stand that close on the train do you?

if ($condition==true) {

Much better. Whilst we are at it, the same applies to the operands and operators inside the if statement:

if ($condition == true) {
    $var = 4; //Also applies inside code blocks.

2) Tabs not welcome

When using indentations, do not use tabs. If you are using tabs right now, stop immediately. Instead, use 4 spaces.

Most IDE's have a setting that automatically convert tabs into any number of spaces. So find yours.

The reason is because every text editor in the world, from the very primitive vi to the advanced IDEs display 4 spaces in the same way, thus keeping indentations perfect. Tabs, on the other hand, cause lines to pushed all over the place reducing readability on different environment.

3) Indentations

Of course this all assumes that you neatly indent your code to begin with.

The rule is simple: for every new code block, 4 spaces should be added within the code block:

 if ($condition == true) {
     while ($otherCondition != false) {
         $var = $this->getArray();
         foreach ($var as $item) {
              switch ($item) {
                  case 0:
                      echo 'hello';
                      echo 'goodbye';
 } else {
     die('couldn't think of any more code');

As you can see it is so easy to see what block each line of code is in. If the blocks were really long, having the indentations improves readability. So please, put indentations properly and consistently.

4) New Line Brackets

This one is a short one. For classes and functions, make the opening bracket on a new line:

class someClass extends someOtherClass
     private $var;

     public function getVar()
         return $this->var;

Not only does it look better, but it also means that I can do what ever I like to the class or function declaration and not worry about the opening bracket.

© 2012-2017