preface

Today, a friend of mine told me about a problem he encountered when developing a requirement with so many criteria that he felt he was writing bad code. In fact, in our development process, it is always inevitable to encounter such a multi-if condition judgment or multiple if-else nesting problem, resulting in code writing becomes very bad. I’ve personally been in this situation a number of times, so I’ve come up with a few tips on how to replace ugly if-else statements in a more elegant way (including switch statements, which I think are pretty bad when they’re too long).

Elegant way

Next, according to a few frequently encountered scenarios, one by one with a more elegant replacement.

withreturnalternativeif-else

Scenario: Mutually exclusive condition judgment

 function test(data){
     let result = ' ';
     if(data<10){
         result = 'if'
     }else{
         result = 'else'
     }
     return result 

 }
Copy the code

We need to use the if-else to make the two conditions mutually exclusive, but we can get rid of the if-else by using the correct return:

 function test(data){
    let result = ' ';
    if(data<10) {return result = 'if'
    }
    return result = 'else'
}
Copy the code

useArrayincludesmethods

Scenario: Multiple conditions correspond to the same processing

 function region(province){
 let result = ""
   if(province === "Guangdong"|| province === "Guangxi"|| province === "Fujian" || province === "Zhejiang" || province === "Yunnan")  
   {
       result = "The south"
   }
   if(province === "Hebei"|| province === "Heilongjiang"|| province === "Liaoning" || province === "Shandong" || province === "Jilin")  
   {
       result = "The north"}}Copy the code

In the above scenario, we through use in the if statement | | the same for a variety of conditions, it is obvious that This code is very bad, especially province = = = “guangdong” | | province = = = “guangxi” | | province = = = “fujian” | | province = = = “zhejiang” | | in yunnan province = = = “this a string) This scenario can be avoided with Array includes:

  function region(province){
     let result = ""
     let northProvinceArr = ["Hebei"."Heilongjiang"."Liaoning"."Shandong"."Jilin"]
     let southProvinceArr = ["Guangdong"."Guangxi"."Fujian"."Zhejiang"."Yunnan"]
     if(southProvinceArr.includes(province)) result = "The south";
     if(northProvinceArr.includes(province)) result = "The north"
 }
Copy the code

By doing this, our final code looks a lot better;

The strategy pattern

Scene: Juxtaposition of multiple conditions

  function permission(role){
    if(role === "operations"){getOperationPermission()}else if(role === "admin"){
        getAdminPermission()
    }else if(role === "superAdmin"){
        getSuperAdminPermission()
    }else if(role === "user"){
       getUserPermission() 
    }
  }
Copy the code

In this case, we are using the if-else method to determine multiple conditions, but you might use the switch statement to determine multiple conditions:

   function permission(role){
      switch(role){
          case "operations": {
              getOperationPermission();
              break;
          }
          case "admin": {
              getAdminPermission();
              break;
          }
          case "superAdmin": {
              getSuperAdminPermission();
              break;
          }
          case "user": {
              getUserPermission();
              break; }}}Copy the code

Although this method makes the code a lot clearer, I still feel that it is not qualified. Let’s take a look at the results after adopting the strategy mode:

   function permission(role){
       const actions = {
           operations: getOperationPermission,
           admin: getAdminPermission,
           superAdmin: getSuperAdminPermission,
           user: getUserPermission,
       }
       actions[role].call()
  }  
Copy the code

The strategy pattern is clearly more elegant than the previous two.

An array of objects

Scenario: Multiple conditions nested with multiple branching judgments

Code is trickiest when we need to make multiple conditions, with multiple subconditions within each condition. If you don’t get it right, your code will be incredibly bad:

   function getAmount(type,quantity,price){
       let result = 0;
       if(type === "shoe") {if(quantity>5){
             result = price * quantity * 0.7 
           }else{
             result = price * quantity * 0.8}}else{
           if(quantity>5){
             result = price * quantity * 0.9 
           }else{
             result = price * quantity * 0.95}}}Copy the code

In this case, using an array of objects can get a better optimization effect:

   function getAmount(type,quantity,price){
       let result = 0;
       const isShoe = type === "shoe";
       const greater = quantity>5;
       const discountArr = [
          {isShoe: true.greater: true.amount: 0.7 * quantity * price }
          {isShoe: true.greater: false.amount: 0.8 * quantity * price }
          {isShoe: false.greater: true.amount: 0.9 * quantity * price }
          {isShoe: false.greater: false.amount: 0.95 * quantity * price }
       ]
       result = discountArr.filter(item= >
       item.isShoe === isShoe && item.greater === greater)[0].amount
           
   }
Copy the code

Ternary expression

As a side note here, ternary expressions can be a good choice for conditional judgments in some situations to keep your code cleaner (although in my opinion, they’re not that different from if-else in nature) :

    if(a>0){
        a+=1;
    }else{
        a-=1
    }
Copy the code

Ternary expression:

  a>0? a+=1 : a-=1;
Copy the code

However, using ternary expressions for too many complex conditions can backfire.

At the end

The techniques described above are designed to give you a sense of how they work. Specific applications need to be analyzed in the context of actual business scenarios and then optimized to write more elegant code. Finally, I hope my share can be helpful to you!