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.