Refactoring Code For Readability

Published on July 29, 2015

I recently read a post on medium.com where the author refactored this:

<?php

// data
$a = [
    ['n'=>'John Smith', 'dob'=>'1988-02-03'],
    ['n'=>'Jane Jones', 'dob'=>'2014-07-08']
];

// iterate the array
for($x=0;$x<sizeof($a);$x++){/*calculate difference*/$a[$x]['a']=(new DateTime())->diff(new DateTime($a[$x]['dob']))->format("%y");}

into this:

<?php

$users = [
    ['name'=>'John Smith', 'birthday'=>'1988-02-03'],
    ['name'=>'Jane Jones', 'birthday'=>'2014-07-08']
];

// Calculate and store the age in years of each user
foreach($users as &$user) { 
    $today = new DateTime();
    $birthday = new DateTime($user['birthday']);
    $age = $today->diff($birthday);
    $user['age'] = $age->format("%y");
}

unset($user);

However, I'd like to take this at least one step further...

Make the code practically self-commenting:

<?php

$users = [
    ['name' => 'John Smith', 'birthday' => '1988-02-03'],
    ['name' => 'Jane Jones', 'birthday' => '2014-07-08']
];

foreach ($users as &$user) {    
    $user['age'] = calculateAgeOfUser($user);
}

function calculateAgeOfUser(array $user)
{
    $today = new DateTime();
    $birthday = new DateTime($user['birthday']);

    return $today->diff($birthday)->format("%y");
}

Now the code is literally redundant if you keep the comment. The code very nearly reads "for each user calculate age of user."

However, as pointed out by Roland Awemo, there is still some ambiguity. Lets make things a little clearer by making a User object:

<?php

class User
{
    private $name;
    private $birthday;

    public function __construct($name, DateTime $birthday)
    {
        $this->name = $name;
        $this->birthday = $birthday;
    }

    public function calculateAge()
    {
        return $this->birthday->diff(new DateTime)->format("%y");
    }
}

And then update our code:

<?php

$users = [
    new User('John Smith', new DateTime('1988-02-03')),
    new User('Jane Jones', new DateTime('2014-07-08'))
];

foreach ($users as $user) { 
    echo $user->calculateAge();
}