if (condition) {
// do something
} else if (otherCondition) {
// do something else
} else {
// Default
}
通常If-Else逻辑如上所示,但实际却是可以优化的。
1. Remove unnecessary else
public void test(int input) {
if (input > 10) {
// do something
} else {
// do something else
}
}
逻辑结构为if-else,通过return 即可实现优化。
public void test(int input) {
if (input > 10) {
// do something
return ;
}
// do something else
}
实际上根本不需要其他块,在满足特定条件的情况下执行某些操作并立即返回。
2. 价值分配
public String test(int input) {
String gender = "";
if (input == 0) {
gender = "male";
} else if (input == 1) {
gender = "female";
} else {
gender = "unknown";
}
return gender;
}
如果已经找到正确的值,则继续测试一个值就是毫无意义的。因此,代码优化如下:
public String test(int input) {
if (input == 0) return "male";
if (input == 1) return "female";
return "unknown";
}
3. 前提条件查询
通常,如果出现无效值,则方法执行就是毫无意义的。
例如,test方法的有效输入值必须为0或1。
// input must be 0 or 1
public String test(int input) {
// execute logic
}
因此,在允许方法执行之前需要执行一些先决条件。
首先检查输入值,然后执行方法体。
// input must be 0 or 1
public String test(int input) {
if (input < 0) throw new ArithmeticException();
if (input > 1) throw new ArithmeticException();
return input == 0 ? "male" : "female";
}