java優(yōu)化if-else的11種方案
1. 使用早返回(Early Return)
盡可能早地返回,避免嵌套的if-else。
優(yōu)化前:
public class NoEarlyReturnExample {
public boolean hasPositiveNumber(int[] numbers) {
boolean foundPositive = false;
for (int number : numbers) {
if (number > 0) {
foundPositive = true;
// 沒有早返回,而是繼續(xù)循環(huán)
}
}
return foundPositive; // 循環(huán)結(jié)束后返回結(jié)果
}
}優(yōu)化后:
public class EarlyReturnExample {
public boolean hasPositiveNumber(int[] numbers) {
for (int number : numbers) {
if (number > 0) {
return true; // 找到正數(shù)立即返回
}
}
return false; // 沒有找到正數(shù)
}
}減少了多次循環(huán)
2. 使用三元運(yùn)算符
在條件簡單的情況下,可以使用三元運(yùn)算符來簡化代碼。
優(yōu)化前:
public class NoTernaryOperatorExample {
public String getGender(int number) {
if (number > 0) {
return "girl";
} else if (number < 0) {
return "boy";
} else {
return "other";
}
}
}優(yōu)化后:
public class TernaryOperatorExample {
public String getGender(int number) {
return (number > 0) ? "girl" : (number < 0) ? "boy" : "other";
}
}3. 使用switch-case語句
如果你的條件是基于不同的情況或值,更好的選擇是switch-case。
優(yōu)化前:
public class NoSwitchCaseExample {
public void performAction(String action) {
if ("start".equals(action)) {
System.out.println("Starting...");
} else if ("stop".equals(action)) {
System.out.println("Stopping...");
} else {
System.out.println("Unknown action");
}
}
}優(yōu)化后:
public class SwitchCaseExample {
public void performAction(String action) {
switch (action) {
case "start":
System.out.println("Starting...");
break;
case "stop":
System.out.println("Stopping...");
break;
default:
System.out.println("Unknown action");
}
}
}4. 使用策略模式
將每個(gè)條件分支封裝成一個(gè)策略對象,然后根據(jù)條件選擇使用哪個(gè)策略。
優(yōu)化前:
public class NoStrategyExample {
public void context() {
// 沒有使用策略模式,而是直接執(zhí)行代碼
System.out.println("Direct execution");
// do something...
}
}優(yōu)化后:
public class StrategyExample {
interface Strategy {
void execute();
}
public class ConcreteStrategyA implements Strategy {
public void execute() {
System.out.println("Strategy A executed");
}
}
public void context(Strategy strategy) {
strategy.execute();
}
}5. 使用查找表
對于固定數(shù)量的條件分支,可以使用查找表(例如字典或哈希表)來映射條件和對應(yīng)的行為。
優(yōu)化前:
public class NoLookupTableExample {
public void performAction(String action) {
// 沒有使用查找表,而是使用if-else
if ("start".equals(action)) {
System.out.println("Starting...");
} else if ("stop".equals(action)) {
System.out.println("Stopping...");
} else {
System.out.println("No action found");
}
}
}優(yōu)化后:
public class LookupTableExample {
public void performAction(Map<String, Runnable> actions, String key) {
actions.getOrDefault(key, () -> System.out.println("No action found")).run();
}
}6. 使用函數(shù)或方法
將每個(gè)條件分支的邏輯封裝到不同的函數(shù)或方法中,然后在if-else中調(diào)用這些函數(shù)。
優(yōu)化前:
public class NoFunctionExample {
public void handleUserType(String userType) {
// 沒有使用函數(shù)封裝,而是直接在if-else中編寫邏輯
if ("admin".equals(userType)) {
System.out.println("Admin logic here");
} else if ("user".equals(userType)) {
System.out.println("User logic here");
} else {
System.out.println("Guest logic here");
}
}
}優(yōu)化后:
public class FunctionExample {
public void handleUserType(String userType) {
if ("admin".equals(userType)) {
handleAdmin();
} else if ("user".equals(userType)) {
handleUser();
} else {
handleGuest();
}
}
private void handleAdmin() {
System.out.println("Handling admin");
}
private void handleUser() {
System.out.println("Handling user");
}
private void handleGuest() {
System.out.println("Handling guest");
}
}這個(gè)是大家比較常用的,通過不同的功能拆分成不同的函數(shù)。
7. 使用命令模式
將每個(gè)條件分支封裝成一個(gè)命令對象,然后根據(jù)條件執(zhí)行相應(yīng)的命令。
優(yōu)化前:
public class NoCommandExample {
public void performAction(String action) {
// 直接執(zhí)行動(dòng)作,沒有使用命令模式
if ("start".equals(action)) {
System.out.println("Starting...");
} else if ("stop".equals(action)) {
System.out.println("Stopping...");
}
}
}優(yōu)化后:
public class CommandExample {
interface Command {
void execute();
}
public class StartCommand implements Command {
public void execute() {
System.out.println("Starting...");
}
}
public class StopCommand implements Command {
public void execute() {
System.out.println("Stopping...");
}
}
public void executeCommand(Command command) {
command.execute();
}
}8. 使用狀態(tài)模式
如果邏輯分支與狀態(tài)有關(guān),可以使用狀態(tài)模式來管理狀態(tài)轉(zhuǎn)換。
優(yōu)化前:
public class NoStateExample {
public void handleAction(String state) {
// 沒有使用狀態(tài)模式,直接在代碼中處理邏輯
if ("start".equals(state)) {
System.out.println("Handling start");
} else if ("stop".equals(state)) {
System.out.println("Handling stop");
}
}
}優(yōu)化后:
public class StateExample {
interface State {
void handle();
}
public class StartState implements State {
public void handle() {
System.out.println("Handling start state");
}
}
public class StopState implements State {
public void handle() {
System.out.println("Handling stop state");
}
}
public class Context {
private State state;
public void setState(State state) {
this.state = state;
}
public void request() {
state.handle();
}
}
}狀態(tài)轉(zhuǎn)換類似于我們在做一個(gè)簡單的工單流轉(zhuǎn),每一步都是確定且可復(fù)用的場景。
9. 重構(gòu)條件表達(dá)式
檢查是否可以將復(fù)雜的條件表達(dá)式分解為更簡單的部分。
優(yōu)化前:
public class UnrefactoredConditionExample {
public boolean isWeekend(int day) {
// 沒有重構(gòu)的條件表達(dá)式,切套多、不好閱讀
if (day == 6 || (day == 7 && !isHoliday(day))) {
return true;
}
return false;
}
private boolean isHoliday(int day) {
// 法定的假日檢查邏輯(法定節(jié)假日每年都在變)
return false;
}
}優(yōu)化后:
public class RefactoredConditionExample {
public boolean isWeekend(int day) {
return day == 6 || day == 7;
}
}
簡潔了很多
10. 使用斷言
在某些情況下,使用斷言來確保代碼的預(yù)設(shè)條件被滿足,避免復(fù)雜的條件判斷。
優(yōu)化前:
public class NoAssertExample {
public void process(int value) {
if (value <= 0) {
throw new IllegalArgumentException("Value must be positive");
}
// 處理邏輯
System.out.println("Processing value: " + value);
}
}
優(yōu)化后:
public class AssertExample {
public void process(int value) {
assert value > 0 : "Value must be positive";
// 處理邏輯
System.out.println("Processing value: " + value);
}
}
多數(shù)編程中,斷言被用在自動(dòng)化測試用例。不過預(yù)設(shè)條件判斷用起來也非常絲滑。
11. 使用異常處理
在某些情況下,使用異常處理來簡化錯(cuò)誤條件的處理。
優(yōu)化前:
public class NoExceptionHandlingExample {
public int divide(int dividend, int divisor) {
if (divisor == 0) {
// 沒有使用異常處理,而是直接返回錯(cuò)誤代碼
System.out.println("Cannot divide by zero");
return -1;
}
return dividend / divisor;
}
}
優(yōu)化后:
public class ExceptionHandlingExample {
public int divide(int dividend, int divisor) {
try {
return dividend / divisor;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
return -1;
}
}
}
當(dāng)遇到異常,盡可能在合適的地方捕獲并處理,不要直接把所有異常都拋到最外層。
到此這篇關(guān)于java優(yōu)化if-else的11種方案的文章就介紹到這了,更多相關(guān)java優(yōu)化if-else內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java 本地方法Native Method詳細(xì)介紹
這篇文章主要介紹了 Java 本地方法Native Method詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2017-02-02
Java SPI機(jī)制原理與實(shí)戰(zhàn)技巧
這段文章深入解析了JavaSPI機(jī)制原理與實(shí)戰(zhàn),涵蓋基本原理、代碼實(shí)戰(zhàn)及優(yōu)化方案,重點(diǎn)介紹了資源管理、異常處理、日志規(guī)范和單元測試的最佳實(shí)踐,助你寫出高質(zhì)量代碼,感興趣的朋友一起看看吧2026-06-06
SpringMVC結(jié)合ajaxfileupload.js實(shí)現(xiàn)文件無刷新上傳
這篇文章主要介紹了SpringMVC結(jié)合ajaxfileupload.js實(shí)現(xiàn)文件無刷新上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10

