A Guide To Witting Cleaner Code

A Guide To Witting Cleaner Code

Given Ncube

If statements often cause a problem in your code in terms of readability and the amount of code you write. In this article, I'm going to show you how to write better if statements.

Sometimes you end up nesting up to 3 if statements like this

<?php

function do_some_stiff($arg){
if(is_string($arg)){
    if(some_condition){
        if(some_condition){
            //code
        } esle{
        //code
        }
    } elseif(some_other_condition) {
    if(som_condition){
         //code
         }
    } else{
    //code
    }
}

That's probably the worst nested if block ever, you don't do that do you. I couldn't come up with an appropriate example for that. But anyway, we can make that code better more readable. To do that, we need to check for what we don't want in our if statements. Let's look at an example.

function some_func(){
    if(!some_condition){
       //code
     }
}

Makes little sense, right? It will soon. We have to end our program if we have what we don't want, in case of a function we return. Let's take a look

function some_func(){
    if(!some_condition){
      return;
     }
     //we're all set let's continue execution
}

If you have to check for several conditions before you do a task you can do it like this

function some_func(){ if(!some_condition){ return; }

if(!some_condition){
  return;
 }

 if(!some_condition){
  return;
 }
 //we're all set let's continue execution

}


Now if your code makes it all the way to the end, it means everything went well. I hope this article will help you write better if statements. If you have code blocks similar to the one we have above there, you can always refactor. Just remember before you nest any if statements ask yourself how can I use only if statement and return.

Lasting

Digital

Impressions

Subscribe to our newsletter

Subscribe to our newsletter to get the latest updates on our projects and services.

About

Flixtechs is a Laravel web development agency in Harare, Zimbabwe. We are a team of young and passionate developers who are always ready to help you build your dream website.

© 2023 Flixtechs. All rights reserved.