logo

Improve bad code

How to recognize bad code?

December 13, 2014

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.

So let’s focus on both cases to see where this big difference comes from.

Untested code

Untested code is the code for which no tests exist. Depending on the quality of the code, this can be overcome quickly and easily or slowly and painfully. Let’s jump straight into an example in CompanyX.

<?php
 
namespace \CompanyX;
 
class CokeDispenser {
    public function getCoke() {
        return 'coke';
    }
}

The class CokeDispenser is a very simplified class and the following is a test written in PHPUnit that shows how easy it is to write a test that validates this class.

<?php
 
use \CompanyX\CokeDispenser;
 
class CokeDispenserTest extends PHPUnit_Framework_TestCase {
 
    /**
    * @before
    */
    public function setUp() {
        $this->cokeDispenser = new CokeDispenser();
    }
 
    /**
    * @test
    */
    public function shouldReturnACokeWhenGetCokeIsCalled()
    {
        $expectedResult = 'coke';
        $this->assertEquals($expectedResult, $this->cokeDispenser->getCoke());
    }
}

Untestable code

The previous example code was intentionally very simple, but that should be your goal when designing your code. Keeping things simple and straightforward is the key in making your designs testable. Cutting corners and hacking your way without taking the time to think the design through will mostly result in untestable code. And combining loads of untestable code will eventually mount up into what we like to call spaghetti code, which is a pile of disorganized coding mess. A developers hell if you’d like and in time, such code starts to rot, scaring novice developers away.

It also discourages better developers from diving in, since such code will clearly require a lot of effort upfront before it will become graspable and maintainable. So let’s take a look at some untestable code.

<?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';
        }
    }
}

This code looks quite simple and clean, but testing or extending it is a nightmare. We’ll take a closer look in the next post . Can you spot what’s wrong with it? Write your comments below. Until next time!