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.

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.

Stay up to date with all things Laravel, PHP, and JavaScript.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

Angel Brown avatar

Such an awesome post. Thanks for sharing this one! concrete driveway Port Charlotte Fl

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.