if else 是我们写代码时,使用频率最高的关键词之一,然而有时过多的 if else 会让我们感到脑壳疼,例如下面这个伪代码:
640.webp
是不是很奔溃?虽然他是伪代码,并且看起来也很夸张,但在现实中,当我们无数次 review 别人代码时,都会发现类似的场景,那么我们本文就来详细聊聊,有没有什么方法可以让我们避免来写这么多的 if else 呢?

1.使用 return

我们使用 return 去掉多余的 else,实现代码如下。
优化前代码:

  1. if (str.equals("java")) {
  2. // 业务代码 ! true;
  3. } else {
  4. return ;
  5. }

优化后代码:

  1. if (str.equals("java")) {
  2. return ;
  3. }
  4. return false;

2.使用 Map

使用 Map 数组,把相关的判断信息,定义为元素信息可以直接避免 if else 判断,实现代码如下。
优化前代码:

  1. if (t == 1) {
  2. type = "name";
  3. } else if (t == 2) {
  4. type = "id";
  5. } else if (t == 3) {
  6. type = "mobile";
  7. }

我们先定义一个 Map 数组,把相关判断信息存储起来:

  1. Map<Integer, String> typeMap = new HashMap<>();
  2. typeMap.put(1, "name");
  3. typeMap.put(2, "id");
  4. typeMap.put(3, "mobile");

之前的判断语句可以使用以下一行代码代替了:

  1. type = typeMap.get(ty);

3.使用三元运算符

三元运算符也叫三元表达式或者三目运算符/表达式,不过代表的都是一个意思,优化代码如下。
优化前代码:

  1. Integer score = 81;
  2. if (score > 80) {
  3. score = 100;
  4. } else {
  5. score = 60;
  6. }

优化后代码:

  1. score = score > 80 ? 100 : 60;

4.合并条件表达式

在项目中有些逻辑判断是可以通过梳理和归纳,变更为更简单易懂的逻辑判断代码,如下所示。
优化前代码:

  1. String city = "西安";
  2. String area = "029";
  3. String province = "陕西";
  4. if ("西安".equals(city)) {
  5. return "xi'an";
  6. }
  7. if ("029".equals(area)) {
  8. return "xi'an";
  9. }
  10. if ("陕西".equals(province)){
  11. return "xi'an";
  12. }

优化后代码:

  1. if ("西安".equals(city) || "029".equals(area) || "陕西".equals(province)){
  2. return "xi'an";
  3. }

5.使用枚举

JDK 1.5 中引入了新的类型——枚举(enum),我们使用它可以完成很多功能,例如下面这个。
优化前代码:

  1. Integer typeId = 0;
  2. String type = "Name";
  3. if ("Name".equals(type)) {
  4. typeId = 1;
  5. } else if ("Age".equals(type)) {
  6. typeId = 2;
  7. } else if ("Address".equals(type)) {
  8. typeId = 3;
  9. }

优化时,我们先来定义一个枚举:

  1. public enum TypeEnum {
  2. Name(1), Age(2), Address(3);
  3. public Integer typeId;
  4. TypeEnum(Integer typeId) {
  5. this.typeId = typeId;
  6. }
  7. }

之前的 if else 判断就可以被如下一行代码所替代了:

  1. typeId = TypeEnum.valueOf("Name").typeId;

6.使用 Optional

从 JDK 1.8 开始引入 Optional 类,在 JDK 9 时对 Optional 类进行了改进,增加了 ifPresentOrElse() 方法,我们可以借助它,来消除 if else 的判断,使用如下。
优化前代码:

  1. String str = "java";
  2. if (str == null) {
  3. System.out.println("Null");
  4. } else {
  5. System.out.println(str);
  6. }

优化后代码:

  1. Optional<String> opt = Optional.of("java");
  2. opt.ifPresentOrElse(v ->
  3. System.out.println(v), () -> System.out.println("Null"));

小贴士:注意运行版本,必须是 JDK 9+ 才行。

7.梳理优化判断逻辑

和第 4 点比较类似,我们可以通过分析 if else 的逻辑判断语义,写出更加易懂的代码,例如以下这个嵌套判断的优化。
优化前代码:

  1. // 年龄大于 18
  2. if (age > 18) {
  3. // 工资大于 5000
  4. if (salary > 5000) {
  5. // 是否漂亮
  6. if (pretty == true) {
  7. return true;
  8. }
  9. }
  10. }
  11. return false;

优化后代码:

  1. if (age < 18) {
  2. return false;
  3. }
  4. if (salary < 5000) {
  5. return false;
  6. }
  7. return pretty == true;

8.使用多态

继承、封装和多态是 OOP(面向对象编程)的重要思想,本文我们使用多态的思想,提供一种去除 if else 方法。
优化前代码:

  1. Integer typeId = 0;
  2. String type = "Name";
  3. if ("Name".equals(type)) {
  4. typeId = 1;
  5. } else if ("Age".equals(type)) {
  6. typeId = 2;
  7. } else if ("Address".equals(type)) {
  8. typeId = 3;
  9. }

使用多态,我们先定义一个接口,在接口中声明一个公共返回 typeId 的方法,在添加三个子类分别实现这三个子类,实现代码如下:

  1. public interface IType {
  2. public Integer getType();
  3. }
  4. public class Name implements IType {
  5. @Override
  6. public Integer getType() {
  7. return 1;
  8. }
  9. }
  10. public class Age implements IType {
  11. @Override
  12. public Integer getType() {
  13. return 2;
  14. }
  15. }
  16. public class Address implements IType {
  17. @Override
  18. public Integer getType() {
  19. return 3;
  20. }
  21. }

注意:为了简便我们这里把类和接口放到了一个代码块中,在实际开发中应该分别创建一个接口和三个类分别存储。
此时,我们之前的 if else 判断就可以改为如下代码:

  1. IType itype = (IType) Class.forName("com.example." + type).newInstance();
  2. Integer typeId = itype.getType();

9.选择性的使用 switch

很多人都搞不懂 switch 和 if else 的使用场景,但在两者都能使用的情况下,可以尽量使用 switch,因为 switch 在常量分支选择时,switch 性能会比 if else 高。
if else 判断代码:

  1. if (cmd.equals("add")) {
  2. result = n1 + n2;
  3. } else if (cmd.equals("subtract")) {
  4. result = n1 - n2;
  5. } else if (cmd.equals("multiply")) {
  6. result = n1 * n2;
  7. } else if (cmd.equals("divide")) {
  8. result = n1 / n2;
  9. } else if (cmd.equals("modulo")) {
  10. result = n1 % n2;
  11. }

switch 代码:

  1. switch (cmd) {
  2. case "add":
  3. result = n1 + n2;
  4. break;
  5. case "subtract":
  6. result = n1 - n2;
  7. break;
  8. case "multiply":
  9. result = n1 * n2;
  10. break;
  11. case "divide":
  12. result = n1 / n2;
  13. break;
  14. case "modulo":
  15. result = n1 % n2;
  16. break;
  17. }