preface

Click to jump to personal blog to view previous articles

In the rapid iteration of the product, due to the pursuit of development speed, we tend to ignore the readability and expansibility of the code. Unreasonable use of if-else condition judgment will greatly improve the complexity of our program, but also make the readability of the code rapidly decline, and the difficulty of maintenance in the later stage will be greatly increased, which really makes people’s head hurt. For example:

// Processing of loan application operation
function check() {
  // Enter the correct user name
  if (this.checkUsername(this.username)) {
    // Enter the correct id number
    if (this.checkIdCard(this.idCard)) {
      // Please enter the correct phone number
      if (this.checkTel(this.tel)) {
        // The guarantor is myself
        if (this.dbr === 'Guarantor is I') {
          // Check whether there is a positive id card
          if (document.querySelector('.sfzzm img')) {
            console.log('Present on front of ID card')
            // Check whether there is a reverse side of id card
            if (document.querySelector('.sfzfm img')) {
              console.log('On the wrong side of my id card')
              // Do you have a diploma
              if (document.querySelector('.xlzs img')) {
                console.log('Existing academic certificate')
                if (this.ydxy) {
                  this.tijiaoIsShow = false}}else {
                Toast('Please upload your diploma')
                this.tijiaoIsShow = true}}else {
              Toast('Please upload the reverse side of your ID card')}}else {
            Toast('Please upload the front side of your ID card')}}else if (this.dbr == 'Guarantor is not me') {
          if (this.checkUsername(this.dbrname)) {
            if (this.checkIdCard(this.dbridCard)) {
              if (this.checkTel(this.dbrzyzh)) {
                if (document.querySelector('.sfzzm img')) {
                  console.log('Present on front of ID card')
                  if (document.querySelector('.sfzfm img')) {
                    console.log('On the wrong side of my id card')
                    if (document.querySelector('.xlzs img')) {
                      console.log('Existing academic certificate')
                      this.tijiaoIsShow = false
                    } else {
                      Toast('Please upload your diploma')}}else {
                    Toast('Please upload the reverse side of your ID card')}}else {
                  Toast('Please upload the front side of your ID card')}}else {
                Toast('Please enter the exhibition certificate number of the guarantor')}}else {
              Toast('Please enter the id number of the guarantor')}}else {
            Toast('Please enter the name of guarantor')}}else {
          Toast('Please choose whether the guarantor is myself')}}else {
        Toast('Please enter the correct telephone number')}}else {
      Toast('Please enter the correct ID number')}}else {
    Toast('Please enter the correct name')}}Copy the code

If you were handed a piece of code like this, you’d feel the same way:

This article summarizes the following if-else optimization scenarios to help you.

  • Single if statement optimization
  • If /else statement optimization
  • Single if multi-condition optimization
  • Multiple ELSE if branches are optimized

Single if statement optimization

Before optimization

if (flag) {
 this.handleFn()
}
Copy the code

The optimized

flag && this.handleFn()
// handleFn is a normal function
Copy the code

This writing method is more clear, concise, easy to read!

In addition, if there are many if statements that execute the same function, we can use “logic and” or “logic or” to combine them into a single expression. If our independent conditional judgments can be viewed as scenarios of the same check, the intent of one check is clearly superior to the readability of multiple conditional checks. Let’s look at a code snippet:

if(! (staffInfo.patientName && staffInfo.phone)) {// doSomething}...if(! (staffInfo.phone && staffInfo.idCardNum)) {// doSomething
}
Copy the code

We can modify the above code to look like this by merging the logic:

if(! (staffInfo.patientName && staffInfo.phone) || ! (staffInfo.phone && staffInfo.idCardNum)){// doSomething
} 
Copy the code

If /else statement optimization

If /else can be said to be encountered most frequently in a project, and these two strategies can usually be optimized

  • The policy
  • Ternary operator

The policy

For example, in the user login scenario, if the user name and password input fields are empty, the user is prompted “User name and password cannot be empty”. If there is a value, the login operation is performed.

Before optimization

    if (user && password) {
        // Logical processing
    } else {
        throw('Username and password cannot be empty! ')}Copy the code

The optimized

if(! user || ! password)return throw('Username and password cannot be empty! ')
// Logical processing
Copy the code

When submitting a form, we need to exclude the contents that are not submitted in accordance with our requirements in advance. Usually, when the form submission meets our requirements more than we submit successfully, the exclusion strategy is a good choice.

Ternary operator

The sample a

Let allow = null if (age >= 18) {allow = 'pass '; } else {allow = 'reject '; } let allow = age >= 18? 'Pass' : 'reject'Copy the code

Example 2

if (flag) {
 success();
} else {
 fail();
}
  
/ / after optimization
flag ? success() : fail();
Copy the code

Ternary operators require only one line of code compared to if/else.

Single if multi-condition optimization

Before optimization

function test(type) {
  if (type === 'jpg' || type === 'png' || type === 'gif' || type === 'svg') {
    console.log("This file is a picture"); }}Copy the code

The optimized

function test(type) {
    const imgArr = ['jpg'.'png'.'gif'.'svg']
    if (imgArr.includes(type)) {
        console.log("This file is a picture")}}Copy the code

Multiple ELSE if branches are optimized

Multiple Else Ifs are often a poor choice, leading to complex designs, poor code readability, and possibly difficult refactoring.

if (this.type === 'A') {
  this.handleA();
} else if (this.type === 'B') {
  this.handleB();
} else if (this.type === 'C') {
  this.handleC();
} else if (this.type === 'D') {
  this.handleD();
} else {
  this.handleE();
}
Copy the code

We often encounter multiple else if conditional code, and the else if code gets bigger and bigger as the logic complexity increases.

Take a look at the logic drawn as a flow chart

As you can see from the above flow chart, the code with different conditional branches has a high degree of coupling. Previous conditional judgments affect subsequent code flow and such code is difficult to maintain in subsequent development. We can optimize code with switches, key-values, and maps.

switch

  switch(val){
    case 'A':
      handleA()
      break
    case 'B':
      handleB()
      break
    case 'C':
      handleC()
      break
    case 'D':
      handleD()
      break
  }
Copy the code

Take a look at the logic drawn as a flow chart

Flowcharts are obviously simpler. Furthermore, there is no nesting between the different conditional branches, and they are independent of each other. The logic is clear.

key-value

While the switch statement is logically simpler than the else if statement, the code itself is a bit much.

In fact, our object enumerates key values that associate a condition with a particular operation.

let enums = {
  'A': handleA,
  'B': handleB,
  'C': handleC,
  'D': handleD,
  'E': handleE
}
function action(val){
  let handleType = enums[val]
  handleType()
}
Copy the code

Flow chart:

This approach eliminates all conditional statements and uses key-value objects to store the relationship between conditions and operations. When we need to execute code based on conditions, we no longer need to use an else if or switch statement to handle the corresponding action, we can simply extract the corresponding function handleType from it and execute it.

Map

In fact, we can use maps to further optimize our code.

Map has many advantages over Object

  • The key of an object can only be a string or symbol, whileMapCan be any type of value.
  • We can useMap sizeEasy access to attributesMapThe number of key/value pairs of the object can only be determined manually.
  • Has extremely fast search speed.

The above example can be optimized as follows:

let enums = new Map([['A', handleA],
  ['B', handleB],
  ['C', handleC],
  ['D', handleD],
  ['E', handleE]
])

function action(val){
  let handleType = enums(val)
  handleType()
}
Copy the code

If we encounter multiple layers of complex conditions, the Map statement is even more advantageous!

if (mode == 'kline') {
    if (this.type === 'A') {
        this.handleA()
    } else if (this.type === 'B') {
        this.handleB()
    } else if (this.type === 'C') {
        this.handleC()
    } else if (this.type === 'D') {
        this.handleD()
    }
} else if ((mode = 'depth')) {
    if (this.type === 'A') {
        this.handleA()
    } else if (this.type === 'B') {
        this.handleB()
    } else if (this.type === 'C') {
        this.handleC()
    } else if (this.type === 'D') {
        this.handleD()
    }
}
Copy the code

For such a complex scenario as described above, can Map be used to optimize it?

All we really need to do is concatenate the different judgment statements into a string so that we can associate conditions and actions in key-value format.

let enums = new Map([['kline_A', handleKlineA],
  ['kline_B', handleKlineB],
  ['kline_C', handleKlineC],
  ['kline_D', handleKlineD],
  ['kline_E', handleKlineE],
  ['depth_A', handleDepthA],
  ['depth_B', handleDepthB],
  ['depth_C', handleDepthC],
])

function action(mode, type){
  let key = `${mode}_${type}`
  let handleType = enums(key)
  handleType()
}
Copy the code

Instant is much simpler and clearer, there is no ~ ~ ~

Refer to the article

  • If-else refactoring optimization
  • If-else logic decision optimization
  • How to Use if-else
  • Javascript conditional statement optimization strategy
  • Simple code optimization -if/else