原则二:不使用else关键字

时间:2020-11-27 17:01:01

else关键字多了以后,当增加新需求时,很容易令人不由自主地去增加新的if...else子句,而不是去重构代码。而且,这种条件判断较多的地方,很容易出现代码重复的现象。

例一:

应用原则之前:

public static void endMe() {
    if (status == DONE) {
         doSomething();
    } else {
        <other code>
    }
}

应用原则之后:

public static void endMe() {
  if (status == DONE) {
      doSomething();
      return;
  }
  <other code>
}

else少的话,还可以让代码更易读。

例二:

应用原则之前:

public static Node head() {
    if (isAdvancing()) { return first; }
    else { return last; }
}

应用原则之后:

public static Node head() {
    return isAdvancing() ? first : last;
}

如果是代码中是需要根据不同的状态来进行不同处理的话,设计模式中的策略模式恰好是解决这类代码重复的好方法。

当然,根据代码中条件子句的不同目的,可以有多种方法来避免使用else。不妨做一下练习,看看能总结出多少种方法来。