Code Tip: Avoid unnecessary else statements

When writing code it is easy to think in a logical way. With conditionals, people often write it as they would think it. If this condition is true then return this value, otherwise return a different value.

However there is a trap that people often fall into and one simple refactor can make the code more readable. If you have this conditional within a method or function that is returning a value, you can often just remove the else condition because if the condition is true it would never hit it in the first place.

Consider the following code:

public function getName()
{
    if ($this->firstName && $this->lastName) {
        return $this->firstName.' '.$this->lastName;
    } else {
        return $this->firstName;
    }
}


This is a perfect example for refactoring.

You will notice that if the user has a first and last name, we return it. Otherwise we just return their first name.

However the else condition is redundant because we are already returning a value if the condition evaluates to true.

Therefore we can refactor this method to remove the else statement.

public function getName()
{
    if ($this->firstName && $this->lastName) {
        return $this->firstName.' '.$this->lastName;
    }
    
    return $this->firstName;
}


By doing this, it removes a level of indentation which makes the code more readable. It's a useful tip to remember and one that I find applying all over the place.