优化 if 条件语句的核心目标是提高可读性、降低复杂度、减少嵌套、提升可维护性。下面从常见场景 + 优化技巧 + 示例来说明。
问题代码(嵌套过深):
if (user != null) {
if (user.isActive()) {
if (user.hasPermission()) {
doSomething();
}
}
}
优化后(卫语句):
if (user == null) return;
if (!user.isActive()) return;
if (!user.hasPermission()) return;
doSomething();
✅ 优点:
问题代码:
if (a > 10) {
if (b > 5) {
doSomething();
}
}
优化后:
if (a > 10 && b > 5) {
doSomething();
}
问题代码:
if ("A".equals(type)) {
handleA();
} else if ("B".equals(type)) {
handleB();
} else if ("C".equals(type)) {
handleC();
}
Map<String, Runnable> map = new HashMap<>();
map.put("A", this::handleA);
map.put("B", this::handleB);
map.put("C", this::handleC);
map.getOrDefault(type, () -> {}).run();
interface Handler {
void handle();
}
class AHandler implements Handler {
public void handle() {}
}
Java 14+
switch (type) {
case "A" -> handleA();
case "B" -> handleB();
case "C" -> handleC();
}
Python
match type:
case "A":
handle_a()
case "B":
handle_b()
问题代码:
if (user != null && user.getAge() > 18 && user.isVerified()) {
...
}
优化后:
if (isLegalUser(user)) {
...
}
boolean isLegalUser(User user) {
return user != null && user.getAge() > 18 && user.isVerified();
}
✅ 提高可读性,方便复用
问题代码:
if (status == 1) {
doA();
}
if (status == 1) {
doB();
}
优化后:
if (status == 1) {
doA();
doB();
}
问题代码:
if (code == 200) {
...
}
优化后:
if (code == HttpStatus.OK) {
...
}
Optional.ofNullable(user)
.filter(User::isActive)
.ifPresent(this::doSomething);
inif status in (200, 201, 204):
...
handler = {
"A": handle_a,
"B": handle_b
}
handler.get(type, lambda: None)()
❌ 不要为了“炫技”牺牲可读性
能提前 return 就别嵌套
能合并条件就别拆
能表驱动就别 if-else 堆
能语义化就别写复杂判断
如果你愿意,可以把具体语言 + 实际代码贴出来,我可以帮你逐行优化并解释原因。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。