In my application, I'm executing a transaction which can be in three different states at the end of the execution:
- Success
- Failure
- Pending
Depending on the state, the application client will want to perform different actions. In the case of success, they will want to retrieve the transaction result (a Widget). In the case of failure, they will want to receive the error reason. In the case that the transaction is pending, they will want to schedule a time to retry. Currently I return an object with the following methods:
public interface Result() {
State getState();
Widget getWidget(); // Success
Reason getFailureReason(); // Failure
Callable<Result> getTask(); // Pending
}
The idea is that the client checks the state of the result object, and invokes the appropriate method depending on it's value, e.g.
if (result.getState() == State.PENDING) {
result.getTask();
}
I was thinking that it might be preferable to use a callback instead, e.g.
public interface TransactionCallback() {
void onFailure(Reason reason);
void onSuccess(Widget widget);
Delay onPending(Delay previous);
}
Where Delay
is a class representing a TimeUnit and period, allowing the application to reschedule the transaction execution. Another alternative is to throw an exception wrapping the failure reason (as it should only fail in exceptional conditions), and keep the onSuccess
and onPending
methods.
So my question to SO is this: is the use of a callback an appropriate pattern for this particular problem, or can anyone suggest something more appropriate?