前言
if else 是我们写代码时,使用频率最高的关键词之一,然而有时过多的 if else 会让我们感到脑壳疼,例如下面这个伪代码:
是不是很奔溃?虽然他是伪代码,并且看起来也很夸张,但在现实中,当我们无数次 review 别人代码时,都会发现类似的场景,那么我们本文就来详细聊聊,有没有什么方法可以让我们避免来写这么多的 if else 呢?
我们本文提供了 6种方法来解决掉那些“烦人”的 if else,一起来看吧。
一、使用 return
我们使用 return 去掉多余的 else,实现代码如下。
优化前代码:
if ("java".equals(str)) {
// 业务代码......
} else {
return;
}
优化后代码:
if (!"java".equals(str)) {
return;
}
// 业务代码......
这样看起来就会舒服很多,虽然相差只有一行代码,但真正的高手和普通人之间的差距就是从这一行行代码中体现出来的。
二、使用三元运算符
三元运算符也叫三元表达式或者三目运算符/表达式,不过代表的都是一个意思,优化代码如下。
优化前代码:
Integer score = 81;
if (score > 80) {
score = 100;
} else {
score = 60;
}
优化后代码:
score = score > 80 ? 100 : 60;
三、使用枚举
优化前代码:
Integer typeId = 0;
String type = "Name";
if ("Name".equals(type)) {
typeId = 1;
} else if ("Age".equals(type)) {
typeId = 2;
} else if ("Address".equals(type)) {
typeId = 3;
}
优化时,我们先来定义一个枚举:
public enum TypeEnum {
Name(1), Age