Return enum is ok. But if you are going to call it from many places, you will have the same error handling code in several areas (i.e. the same switch ).
Perhaps one approach is to return a logical, but encapsulate specific error handling logic inside the error handler. Thus, you define an interface like this:
interface PostErrorHandler { void handle(...); }
Then you can have specific implementations:
public class SpamErrorHandler implements PostErrorHandler { @Override public void handle(...) { ...
Your method signature for publishing will be as follows:
public boolean post(String content, PostErrorHandler handler) { ... }
Then you call handler.handle(...) based on the error starting with post .
If you still want to report an error, you can use the approach you mentioned: return enum instead of a boolean.
Regarding exceptions, more than ugliness, the main reason why using exceptions here is a bad idea is because it seems like errors like this are expected. If so, you expect the caller to deal with them in some way, and they seem to be part of your business logic. But using exceptions is not the correct way to make these errors. Usually you want to use exceptions only if something unexpected happens. If you should throw an exception, then it is better to have some kind of status check / check method that checks the input to warn you if the input is bad. In this case, you can throw an exception (make it unchecked) because the situation is unexpected, since you expect the caller to use the state check method before calling the method.
source share