Home  >  Article  >  Tip sharing: reduce the use of if-else and increase the readability of the code!

Tip sharing: reduce the use of if-else and increase the readability of the code!

青灯夜游
青灯夜游forward
2022-10-27 10:11:222453browse

I believe that everyone has more or less come into contact with project codes with huge if else. Multiple nested if else is really annoying during maintenance. Sometimes after troubleshooting a bug, I feel seriously hollowed out.

This article does not mean to eliminate or discriminate if else, everyone knows the usefulness of if else, here is just for everyone in some specific scenarios Provide an additional idea to increase the readability of our code.

Short-circuit operation

The logic of Javascript or the short-circuit operation of || can sometimes be used to replace some simpler if else

  • Short-circuit operation of logical OR ||: If the left side can be converted to true, the value of the expression on the left is returned, otherwise the value of the expression on the right is returned.

Let’s use a simple case to explain

let c
if(a){
    c = a
} else {
    c = b
}

Everyone will feel uncomfortable looking at the above code (I have some obsessive-compulsive disorder), it is obviously a very simple judgment But it requires writing several lines of code to achieve it. At this time we can use short-circuit operations to simplify our code.

let c = a || b

Doesn’t this look much simpler?.

Ternary operator

I think everyone should be familiar with the ternary operator. Many times we can use the ternary operator to make simple judgments. Instead of if else, only the one-level ternary operator is recommended here, because multi-level nested ternary operators also do not have good readability.

Example: Return 1 when the condition is true, otherwise return 0:

const fn = (nBoolean) {
    if (nBoolean) {
        return 1
    } else {
        return 0
    }
    
}

// 使用三元运算符
const fn = (nBoolean) {
    return nBoolean ? 1 : 0
}

The ternary operator is also used in many places, such as: conditional assignment, recursion...

// num值在nBoolean为true时为10,否则为5
let num = nBoolean ? 10 : 5

// 求0-n之间的整数的和
let sum = 0;
function add(n){
    sum += n
    return n >= 2 ? add(n - 1) : result;
};
let num = add(10);//55

switch case

The above two methods: short-circuit operation and ternary operation are very useful and the code is very concise, but they can only be used for simple judgment. It cannot be used when judging multiple conditions.

For switch case, although its readability is indeed higher than else if, I think everyone thinks it is more troublesome to write (anyway I find it very troublesome).

Example: There are four types: A, B, C, and D. When A and B are output, 1 is output, C outputs 2, and D outputs 3. The default output is 0.

let type = 'A'

//if else if
if (type === 'A' || type === 'B') {
    console.log(1);
} else if (type === 'C') {
    console.log(2);
} else if(type === 'D') {
    console.log(3);
} else {
    console.log(0)
}

//switch case
switch (type) {
    case 'A':
    case 'B':
        console.log(1)
        break
    case 'C':
        console.log(2)
        break
    case 'D':
        console.log(3);
        break;
    default:
        console.log(0)
}

Object configuration/strategy mode

Object configuration looks similar to Strategy mode, both use different data according to different parameters/ Algorithms/functions.

The strategy pattern encapsulates a series of algorithms and makes them interchangeable. The encapsulated algorithm is independent and its characteristics cannot be changed by the outside world.

Next we use the object configuration method to implement the above example

let type = 'A'

let tactics = {
    'A': 1,
    'B': 1,
    'C': 2,
    'D': 3,
    default: 0
}
console.log(tactics[type]) // 1

Next, we will use a few examples to make everyone more familiar.

Case 1 Shopping mall promotional price

Use different discounts according to different users, such as: no discount for ordinary users, 10% off for ordinary members, and 15% off for annual members , 20% off for super members.

Useif elseAchievement

// 获取折扣 --- 使用if else
const getDiscount = (userKey) => {
    if (userKey === '普通会员') {
        return 0.9
    } else if (userKey === '年费会员') {
        return 0.85
    } else if (userKey === '超级会员') {
        return 0.8
    } else {
        return 1
    }
}
console.log(getDiscount('普通会员')) // 0.9

Use object configuration/strategy pattern to achieve?

// 获取折扣 -- 使用对象配置/策略模式
const getDiscount = (userKey) => {
    // 我们可以根据用户类型来生成我们的折扣对象
    let discounts = {
        '普通会员': 0.9,
        '年费会员': 0.85,
        '超级会员': 0.8,
        'default': 1
    }
    return discounts[userKey] || discounts['default']
}
console.log(getDiscount('普通会员')) // 0.9

It can be clearly seen from the above cases, Using object configuration is more readable than using if else. If you need to add user discounts later, you only need to modify the discount object.

Object configuration does not necessarily have to use objects to manage our key-value pairs. You can also use Map to manage?, such as:

// 获取折扣 -- 使用对象配置/策略模式
const getDiscount = (userKey) => {
    // 我们可以根据用户类型来生成我们的折扣对象
    let discounts = new Map([
        ['普通会员', 0.9],
        ['年费会员', 0.85],
        ['超级会员', 0.8],
        ['default', 1]
    ])
    return discounts.get(userKey) || discounts.get('default')
}
console.log(getDiscount('普通会员')) // 0.9

Case 2 Year-end Award

The company's year-end bonus is issued based on the employee's salary base and performance level. For example, the year-end bonus of a person with performance A is 4 times the salary, that of a person with performance B is 3 times, and that of a person with performance C is only 2 times.

If the Finance Department requires us to provide a piece of code to implement this accounting logic, how do we implement it?

Isn’t this very simple? It can be done with just one function.

const calculateBonus = (performanceLevel, salary) => { 
    if (performanceLevel === 'A'){
        return salary * 4
    }
    if (performanceLevel === 'B'){
        return salary * 3
    }
    if (performanceLevel === 'C'){
        return salary * 2
    }
}
calculateBonus( 'B', 20000 ) // 输出:60000

It can be found that this code is very simple, but the calculateBonus function is relatively large. All logical branches are included in the if else statement. If an additional Plant a new performance level D, or change the multiple of level A to 5, then we must read all the code before making changes.

So we can use object configuration/strategy mode to simplify this function

let strategies = new Map([
    ['A', 4],
    ['B', 3],
    ['C', 2]
])
const calculateBonus = (performanceLevel, salary) => { 
    return strategies.get(performanceLevel) * salary
}
calculateBonus( 'B', 20000 ) // 输出:60000

At this point, this requirement is completed, and then the product manager said that a department distinction should be added. Assume that the company has two departments. D and F. Department D has better performance, so the year-end bonus is increased by 1.2 times. Department F has poor performance, so the year-end bonus is discounted by 10%.

Transform the above code, splice the status values, and then store them in the Map

// 以绩效_部门的方式拼接键值存入
let strategies = new Map([
    ['A_D', 4 * 1.2],
    ['B_D', 3 * 1.2],
    ['C_D', 2 * 1.2],
    ['A_F', 4 * 0.9],
    ['B_F', 3 * 0.9],
    ['C_F', 2 * 0.9]
])
const calculateBonus = (performanceLevel, salary, department) => { 
    return strategies.get(`${performanceLevel}_${department}`) * salary
}
calculateBonus( 'B', 20000, 'D' ) // 输出:72000

End

This article is mainly to convey an idea to everyone, We have many ways to optimize our code and improve the readability of our code.

does not mean to discriminate against if else, I just hope that there will be more than just if else in your future code.

For more programming related knowledge, please visit: Programming Video! !

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete