Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the standard pattern for a method that might fail for different reasons? [closed]

Tags:

java

c#

.net

Say I have a method that will post some content online and return true/false representing success/failure.

However, my method can fail at different steps, for example:

  • Blocked by spam blocker
  • Network error
  • Unanticipated exception

I still want the method to simply return a Boolean, I also don't like the idea of letting the method just throw its exception and every caller has to wrap it in a try/catch (I hate try/catch, it's always ugly).

Is there a standard solution for this problem?

The best solution I came up with is to make it return an enum instead with the different possible outcomes, then the caller will have a switch statement. Is there a solution better than this?

EDIT: I should have been more clear; this is an Android app, the user will be posting comments online, the different errors will be translated into messages for the user e.g. "Spam, wait before trying to post again"

like image 924
SpaceMonkey Avatar asked Oct 20 '22 09:10

SpaceMonkey


1 Answers

Returning an enum is fine. But if you're going to be calling this from a lot of places, you're going to have the same error-handling code in multiple areas (i.e., the same switch statement).

Perhaps one approach is to return a boolean, but encapsulate specific error-handling logic inside an error-handler. So you'd define an interface like so:

interface PostErrorHandler {
    void handle(...);
}

Then you can have concrete implementations:

public class SpamErrorHandler implements PostErrorHandler {
    @Override
    public void handle(...) {
        ... //code to deal with spam
    }
}

The signature of your method to post would then be:

public boolean post(String content, PostErrorHandler handler) {
    ...
}

You'd then call handler.handle(...) based on the error, from within post.

If you still want to communicate the kind of error that happened, you can use the approach you mentioned: return an enum instead of a boolean.

As far as exceptions go, more than ugliness, the main reason that using exceptions here is a bad idea is that it looks like these sorts of errors are expected. If so, you are expecting the caller to deal with them in some fashion and they seem to be part of your business logic. But using exceptions is not the correct way these errors. You typically want to use exceptions only if something unexpected happened. If you must throw an exception, then it is better to have some sort of state-inspection/checking method that checks the input to alert you if the input is bad. In that case you can throw an exception (make it unchecked) because the situation is unexpected, since you expect the caller to have used the state-inspection method before calling the method.

like image 161
Vivin Paliath Avatar answered Oct 29 '22 18:10

Vivin Paliath