Conditional statement the safe way

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
}

Continue reading

Conditional statement the readable way

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
}

Continue reading

Untestable code and how-to improve it

Did you find out what was the key culprit of the untestable code segment in my previous post How to recognize bad code?

If you don’t have the time to spend reading the previous article, here’s the problematic code segment again. Let’s just dive straight in.

<?php
 
namespace \CompanyX;
 
class CokeDispenser {
 
    protected $coinCollector;
 
    public function __construct() {
        $this->coinCollector = new CoinCollector();
    }
 
    public function getCoke() {
        if ($this->coinCollector->collectedAmount() >= 2.0) {
            return 'coke';
        }
    }
}

Testability of the code is defined by the openness of the design and loose coupling of the collaborating classes. In this example we can clearly spot two issues.

  1. Actual work in the constructor
  2. Collaborating class instantiation within the class

Both of these issues make testing of the CokeDispenser class difficult, but combined they make it nearly impossible. Let’s take a quick look at why this is bad.
Continue reading

How to recognize bad code?

What is bad code and how to spot it immediately?

A simple description would say bad code equals untested or untestable code. While the former is something that can rather easily be overcome, the latter is a completely different story. It is unfortunately present in many legacy applications and takes a big amount of commitment and knowledge to overcome successfully. Untestable code can quickly find its way into modern applications if we’re not paying attention when designing our code.
Continue reading