gpt4 book ai didi

java - 这是对 try/finally 的滥用吗?

转载 作者:IT老高 更新时间:2023-10-28 20:59:36 24 4
gpt4 key购买 nike

鉴于多个 return 语句是可以接受的(我有点不同意,但 let us digress ),我正在寻找一种更可接受的方式来实现以下行为:

选项A:多次返回,重复代码块

public bool myMethod() {
/* ... code ... */

if(thisCondition) {
/* ... code that must run at end of method ... */
return false;
}

/* ... more code ... */

if(thatCondition) {
/* ... the SAME code that must run at end of method ... */
return false;
}

/* ... even more code ... */

/* ... the SAME CODE AGAIN that must run at end of method ... */
return lastCondition;
}

每次方法返回时看到相同的(小)代码块重复 3 次让我感觉很脏。此外,我想澄清一下,上面的两个 return false 语句当然可以描述为返回中间方法......它们绝对不是“保护语句”。

选项 B 稍微更容易接受吗?我觉得我可能会滥用 try/finally,我希望我应该做一些完全不同的事情。

选项 B:多次返回,try/finally block (没有 catch block /异常)

public bool myMethod() {
try {
/* ... code ... */

if(thisCondition) {
return false;
}

/* ... more code ... */

if(thatCondition) {
return false;
}

/* ... even more code ... */

return lastCondition;
} finally {
/* ... code that must run at end of method ... */
}
}

最后,选项 C 是我的书中最好的解决方案,但我的团队出于某种原因不喜欢这种方法,因此我正在寻找折衷方案。

选项 C:单次返回,条件 block

public bool myMethod() {
/* ... code ... */

if(!thisCondition) {
/* ... more code ... */
}

if(!thisCondition && !thatCondition) {
/* ... even more code ... */
}

/* ... code that must run at end of method ... */
return summaryCondition;
}

如果您想讨论多个返回声明,请在 this question 中进行。 .

最佳答案

如果代码需要在任何其他代码抛出异常的情况下运行,那么 finally block 是正确的解决方案。

如果它不需要在异常情况下运行(即只需要“正常”返回),那么使用 finally 将滥用该功能。

我个人会以单返回点样式重写该方法。不是因为我虔诚地赞同这个想法(我不认同),而是因为它最适合这种方法结束代码。

当代码变得过于复杂时(这是一种非常现实的可能性),是时候通过提取一个或多个方法来重构该方法了。

最简单的重构是这样的:

public boolean  myMethod() {
boolean result = myExtractedMethod();
/* ... code that must run at end of method ... */
return result;
}

protected boolean myExtractedMethod() {
/* ... code ... */

if(thisCondition) {
return false;
}

/* ... more code ... */

if(thatCondition) {
return false;
}

/* ... even more code ... */
return lastCondition;
}

关于java - 这是对 try/finally 的滥用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2230772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com