這篇文章將為大家詳細講解有關在Java項目中使用 if else的技巧有哪些,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
我們使用 return 去掉多余的 else,實現代碼如下。
優化前代碼:
if (str.equals("java")) {
// 業務代碼 ! true;
} else {
return ;
}優化后代碼:
if (str.equals("java")) {
return ;
}
return false;這樣看起來就會舒服很多,雖然相差只有一行代碼,但真正的高手和普通人之間的差距就是從這一行行代碼中體現出來的。
「勿以善小而不為,勿以惡小而為之」「千里之堤,潰于蟻穴」,說的都是同樣的道理。
使用 Map 數組,把相關的判斷信息,定義為元素信息可以直接避免 if else 判斷,實現代碼如下。
優化前代碼:
if (t == 1) {
type = "name";
} else if (t == 2) {
type = "id";
} else if (t == 3) {
type = "mobile";
}我們先定義一個 Map 數組,把相關判斷信息存儲起來:
Map<Integer, String> typeMap = new HashMap<>(); typeMap.put(1, "name"); typeMap.put(2, "id"); typeMap.put(3, "mobile");
之前的判斷語句可以使用以下一行代碼代替了:
type = typeMap.get(ty);
三元運算符也叫三元表達式或者三目運算符/表達式,不過代表的都是一個意思,優化代碼如下。
優化前代碼:
Integer score = 81;
if (score > 80) {
score = 100;
} else {
score = 60;
}優化后代碼:
score = score > 80 ? 100 : 60;
在項目中有些邏輯判斷是可以通過梳理和歸納,變更為更簡單易懂的邏輯判斷代碼,如下所示。
優化前代碼:
String city = "西安";
String area = "029";
String province = "陜西";
if ("西安".equals(city)) {
return "xi'an";
}
if ("029".equals(area)) {
return "xi'an";
}
if ("陜西".equals(province)){
return "xi'an";
}優化后代碼:
if ("西安".equals(city) || "029".equals(area) || "陜西".equals(province)){
return "xi'an";
}JDK 1.5 中引入了新的類型——枚舉(enum),我們使用它可以完成很多功能,例如下面這個。
優化前代碼:
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(2), Address(3);
public Integer typeId;
TypeEnum(Integer typeId) {
this.typeId = typeId;
}
}之前的 if else 判斷就可以被如下一行代碼所替代了:
typeId = TypeEnum.valueOf("Name").typeId;從 JDK 1.8 開始引入 Optional 類,在 JDK 9 時對 Optional 類進行了改進,增加了 ifPresentOrElse() 方法,我們可以借助它,來消除 if else 的判斷,使用如下。
優化前代碼:
String str = "java";
if (str == null) {
System.out.println("Null");
} else {
System.out.println(str);
}優化后代碼:
Optional<String> opt = Optional.of("java");
opt.ifPresentOrElse(v ->
System.out.println(v), () -> System.out.println("Null"));小貼士:注意運行版本,必須是 JDK 9+ 才行。
和第 4 點比較類似,我們可以通過分析 if else 的邏輯判斷語義,寫出更加易懂的代碼,例如以下這個嵌套判斷的優化。
優化前代碼:
// 年齡大于 18
if (age > 18) {
// 工資大于 5000
if (salary > 5000) {
// 是否漂亮
if (pretty == true) {
return true;
}
}
}
return false;優化后代碼:
if (age < 18) {
return false;
}
if (salary < 5000) {
return false;
}
return pretty == true;
我們需要盡量把表達式中的包含關系改為平行關系,這樣代碼可讀性更高,邏輯更清晰。
繼承、封裝和多態是 OOP(面向對象編程)的重要思想,本文我們使用多態的思想,提供一種去除 if else 方法。
優化前代碼:
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;
}使用多態,我們先定義一個接口,在接口中聲明一個公共返回 typeId 的方法,在添加三個子類分別實現這三個子類,實現代碼如下:
public interface IType {
public Integer getType();
}
public class Name implements IType {
@Override
public Integer getType() {
return 1;
}
}
public class Age implements IType {
@Override
public Integer getType() {
return 2;
}
}
public class Address implements IType {
@Override
public Integer getType() {
return 3;
}
}注意:為了簡便我們這里把類和接口放到了一個代碼塊中,在實際開發中應該分別創建一個接口和三個類分別存儲。
此時,我們之前的 if else 判斷就可以改為如下代碼:
IType itype = (IType) Class.forName("com.example." + type).newInstance();
Integer typeId = itype.getType();有人可能會說,這樣反而讓代碼更加復雜了,此可謂“殺雞焉用宰牛刀”的典型范例了。這里作者只是提供一種實現思路和提供了一些簡易版的代碼,以供開發者在實際開發中,多一種思路和選擇,具體用不用需要根據實際情況來定了。靈活變通,舉一反三,才是開發的上乘心法。
很多人都搞不懂 switch 和 if else 的使用場景,但在兩者都能使用的情況下,可以盡量使用 switch,因為 switch 在常量分支選擇時,switch 性能會比 if else 高。
if else 判斷代碼:
if (cmd.equals("add")) {
result = n1 + n2;
} else if (cmd.equals("subtract")) {
result = n1 - n2;
} else if (cmd.equals("multiply")) {
result = n1 * n2;
} else if (cmd.equals("divide")) {
result = n1 / n2;
} else if (cmd.equals("modulo")) {
result = n1 % n2;
}switch 代碼:
switch (cmd) {
case "add":
result = n1 + n2;
break;
case "subtract":
result = n1 - n2;
break;
case "multiply":
result = n1 * n2;
break;
case "divide":
result = n1 / n2;
break;
case "modulo":
result = n1 % n2;
break;
}在 Java 14 可使用 switch 代碼塊,實現代碼如下:
// java 14
switch (cmd) {
case "add" -> {
result = n1 + n2;
}
case "subtract" -> {
result = n1 - n2;
}
case "multiply" -> {
result = n1 * n2;
}
case "divide" -> {
result = n1 / n2;
}
case "modulo" -> {
result = n1 % n2;
}
}關于在Java項目中使用 if else的技巧有哪些就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。