Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Further refactoring code for readability

Original – by Freek Van der Herten – 2 minute read

A few days ago Dylan Bridgman published a post on writing highly readable code. He cleaned up a truly horrible piece of code. The code was further improved the very same day by Ryan Winchester.

I believe the code can be improved still. Read the mentioned blog posts to see which code we are going to improve. Warning: I'm going to nitpick.

The readability of the code can be improved:

  • by adding docblocks to the variables and methods of the class. I makes it very clear what type of parameters are passed an returned.
  • The age variable isn't used. Reading dead code is useless, so let's remove it.
  • Also if the variables or protected instead of private, they can be used when inheriting from the class.
So in my mind this is better: [code language="php"] class User { /** * @var string */ protected $name;
/**
 * @var DateTime
 */
protected $birthday;

/**
 * @param string $name
 * @param DateTime $birthday
 */
public function __construct($name, DateTime $birthday)
{
    $this->name = $name;
    $this->birthday = $birthday;
}

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

}




The last bit of code in Ryan's post is a foreach loop. By using `array_map` instead the variable inside the loop can be typehinted. This further increases readability.
[code language="php"]
array_map(function(User $user) {
   echo $user->calculateAge();
}, $users);

In this case you could argue that using array_map is overkill. But there's a good chance that in production code there isn't an array initialized with the objects just above the loop.

When working with large chunks of code these kind of details matter. Code gets read a lot more times than it is written, so it should be highly optimized for reading.

Share Post LinkedIn

I write about Laravel, PHP, AI and building better software.

Every two weeks, I share practical tips, tutorials, and behind-the-scenes insights from maintaining 300+ open source packages. Join thousands of developers who read along.

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share?

The community section is a place where developers share links to articles, tutorials and videos. Submit a link and help fellow developers discover great content. As a thank you, you'll receive a coupon for a discount on Spatie products.