Given that multiple return statements are acceptable (I disagree, but let us digress), I'm looking for a more acceptable way to achieve the following behavior:
Option A: multiple returns, repeated code block
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;
}
It makes me feel dirty to see the same (little) code block repeated three times each time the method returns. Furthermore, I would like to clarify that the two return false
statements above can certainly be described as returning mid-method... they are absolutely not "guard statements."
Is Option B slightly more acceptable? I feel that I may abusing try/finally, and I'm hoping there is something completely different that I should be doing.
Option B: multiple returns, try/finally block (without catch blocks / exceptions)
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 ... */
}
}
Finally, Option C is the best solution in my book, but my team doesn't like this approach for whatever reason(s), hence I'm looking for a compromise.
Option C: single return, conditional blocks
public bool myMethod() {
/* ... code ... */
if(!thisCondition) {
/* ... more code ... */
}
if(!thisCondition && !thatCondition) {
/* ... even more code ... */
}
/* ... code that must run at end of method ... */
return summaryCondition;
}
If you want to discuss multiple return statements, please do so in this question.