Code that breathes
Original – by Brent Roose & Freek Van der Herten – 2 minute read
Have you ever needed to maintain a project that wasn't yours? A project that, when you first opened it, gave you chills down your spine? Even without reading the code in detail, you could already tell it was a mess.
Maybe you couldn't pinpoint the exact problem, but this code simply looked odd, felt wrong.
Writing clean code; code that you enjoy working in; code that you can come back to, two or three years after writing it, and still feel comfortable changing; that's an art in itself. It's definitely a subjective topic — don't get me wrong; but there are many parts of "writing readable PHP" that can be mastered.
In the next few weeks, I'll focus on small tips that have a big impact on your code. If you're inspired by these tips, and want to dive deeper into the topic of readable code, make sure to head over to writing-readable-php.com and take a look at our full course.
We start our list with a very actionable tip. Take a look at this code:
public function getPage($url)
{
$page = $this->pages()->where('slug', $url)->first();
if (! $page) {
return null;
}
if ($page['private'] && ! Auth::check()) {
return null;
}
return $page;
}
Just like reading text, grouping code in paragraphs can be helpful to improve its readability. We like to say we add some "breathing space" to our code. Have a look:
public function getPage($url)
{
$page = $this->pages()->where('slug', $url)->first();
if (! $page) {
return null;
}
if ($page['private'] && ! Auth::check()) {
return null;
}
return $page;
}
Adding some empty lines to group related bits of code, goes a long way making something readable.