If there is a method
bool DoStuff() {
try {
// doing stuff...
return true;
}
catch (SomeSpecificException ex) {
return false;
}
}
should it rather be called IsStuffDone()
?
Both names could be misinterpreted by the user:
If the name is DoStuff()
why does it return a boolean?
If the name is IsStuffDone()
it is not clear whether the method performs a task or only checks its result.
Is there a convention for this case? Or an alternative approach, as this one is considered flawed? For example in languages that have output parameters, like C#, a boolean status variable could be passed to the method as one and the method's return type would be void
.
EDIT: In my particular problem exception handling cannot be directly delegated to the caller, because the method is a part of an interface implementation. Therefore, the caller can't be charged with dealing with all the exceptions of different implementations. It is not familiar with those exceptions. However, the caller can deal with a custom exception like StuffHasNotBeenDoneForSomeReasonException
as was suggested in npinti's answer and comment.
boolean
instead of wrapping or passing the exception is nearly always wrong.BadlyDesignedMethodInSeriousNeedOfRefactoring
? And to answer your question about the exceptions - I'd either let the caller handle them, or catch them and then throw a custom exception that means "this method no do its job". Share and enjoy.if (FirstMethodSucceeds(problem) or SecondMethodSucceeds(problem) or ...) Hurray(); else UniversalSolve(problem);
. Doing the same with (custom?) exceptions would be uselessly more complicated.