Matok's PHP Blog

How to write IF statement

article image

The best will be show real examples from real code.

First example

$isAdmin = false;

if ($this->authorizationChecker->isGranted('ROLE_ADMIN')) {
    $isAdmin = true;
}

Code above can be rewritten without if at all:

$isAdmin = $this->authorizationChecker->isGranted('ROLE_ADMIN’);

Second example

Check this one, you may try to rewrite it yourself if you came to the same solution as I do.

$showProfile = false;

if ($profile->isPublished()) {
    $showProfile = true;
} else {
    if ($user) {
        if ($this->authorizationChecker->isGranted('ROLE_ADMIN') || ($profile->getUser()->getId() == $user->getId())) {
            $showProfile = true;
        }
    }
}

if (!$showProfile) {
    return $this->getRedirectToListing($profileType, $this->getErrorMsg($profile), 302);
}

This looks like someone start to learn coding…. this code is messy, ugly and really hard to understand what is it doing. There is same expression with authorisationChecked but we got this value in $isAdmin variable (it’s from the same method)

if (!$profile->isPublished() && !($isAdmin || $user && $profile->getUser()->getId() == $user->getId())) {
    return $this->getRedirectToListing($profileType, $this->getErrorMsg($profile), 302);
}

This code is doing the same, but still is not what I like because condition is too long and therefore hard to understand. In situation like is desirable to extract something before if statement.

$isProfileOwner = $user && $profile->getUser()->getId() == $user->getId();

if (!$profile->isPublished() && !($isAdmin || $isProfileOwner)) {
    return $this->getRedirectToListing($profileType, $this->getErrorMsg($profile), 302);
}

With this I am satisfied. Condition can be rewritten using de Morgan rule but this form is more clear. I hope you like code and if you try to write if statements as I do you can save much more time because reading this code is like reading a book.


If you like this article then mark it as helpful to let others know it's worth to read. Otherwise leave me a feedback/comment and we can talk about it.

I'm foreigner. Where I live my friends call me Maťok.


Comments - Coming Soon