You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java最佳实践探讨:优先不可变性还是更清晰的执行流程?

Java代码两种写法的优劣对比咨询

我从事Java代码Pull Requests审核工作已有一段时间,经常遇到如下代码:

String getBar(Foo foo) {
    String bar = "Unknown"; // default value
    if (foo.getBarHandler() != null) {
        bar = foo.getBarHandler().getBar(); // probable mutation
    }
    return bar; // single return
}

这段伪代码的核心逻辑是先初始化默认值bar,可能对其修改后返回。我认为这里的可变性存在弊端,所以总是建议重构为如下写法:

String getBar(Foo foo) {
    if (foo.getBarHandler() == null) { // invert the condition to act like a guard clause
        return "Unknown"; // default value is indented
    }
    return foo.getBarHandler().getBar(); // happy path the least indented
}

不过这种重构方案的缺点是存在两个return语句,可能会让方法的执行流程更难理解。想请教各位,哪种方案更优,原因是什么?

内容的提问来源于stack exchange,提问作者lmo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 23:21:14