Tips for cleaner code: Cleaning up IF statements

This is a video on a practical example of what you can do in your PHP code to clean it up. The maker uses a simple example with if conditions to illustrate an assertive programming.

class User 
{
    public function fullName(){
        if($this->first_name && $this->last_name){
            return $this->first_name .' '. $this->last_name;
        }
        return '';
    }
}

As of assertive programming, we should return the things we expect last, check what could go wrong first. So let's switch things around

class User 
{
    public function fullName(){
        if(!$this->first_name || !$this->last_name){
            return '';
        }
        return $this->first_name .' '. $this->last_name;
    }
}

So in the second case, we are expecting the worst, for either of our names to not be set and we will return an empty string. This is important because it avoids unnecessary nesting of if conditions. Because, in the first case to check some other condition we have to do another if inside the if clause, and another if inside another and so on and so on. So with this simple trick of checking for things to go wrong, we can make our code cleaner.

Here is the first code with some additional conditions to check the length of the names and the content.

class User 
{
    public function fullName(){
        if($this->first_name && $this->last_name){
            if(strlen($this->first_name) > 3 && strlen($this->last_name) > 3){ // let's say we want to make sure the names are atleast 3 chars long
              if(checkOnlyStr($this->first_name) && checkOnlyStr($this->last_name)) { //let's also say we want to check that the names contain only alpahabetic chars
                   return $this->first_name .' '. $this->last_name;
               } else {
                  return '';
               }
            } else {
              return '';
            }
        }
        return '';
    }
}

As you can see, the more conditions we have to check the more complex and messy our code becomes. With assertive code our code would look like this:-

class User 
{
    public function fullName(){
        if(!$this->first_name || !$this->last_name){
            return '';
        }
        if(strlen($this->first_name) < 3 || strlen($this->last_name) < 3){
            return '';
        }
        if(!checkOnlyStr($this->first_name) || !checkOnlyStr($this->last_name)){
            return '';
        }
        return $this->first_name .' '. $this->last_name;
    }
}

By just switching our conditions into checking what could go wrong and returning what we expect at last we can make a huge difference in our code. Get on with it starting now.

Subscribe for coding videos

Keep growing professionally with just three curated videos weekly.

We hate spam as much as you do.