Introduction
In my Java application, I need to represent the result of an operation. This can either be OK or ERROR + an error message.
Background
I have a class to verify the integrity of a directory (e.g. to check that a few conditions hold). If it finds out the directory is corrupted, it should return a description of the error, such as:
- Unexpected file - [filename].
- Unexpected number of files - expected [X], actual [Y].
The callers of the class don't know anything about the directory and the conditions. They are only interested to know if the directory is OK or not, and in that case, to get an appropriate error message.
The Result class was intended as a way to transmit the results of the verification.
I chose not to throw exceptions as (to me) that seemed more convenient for reporting errors in the verification process. It seemed inappropriate to intermix those two situations (e.g. the directory was found invalid vs. an error occurred while verifying the directory).
The current solution
I have so far been able to come up with the following class.
public class Result
{
private static enum State { OK, ERROR };
private State state;
private String errorMessage;
private Result(State state, String errorMessage)
{
this.state = state;
this.errorMessage = errorMessage;
}
public static Result ok()
{
return new Result(State.OK, null);
}
public static Result error(String errorMessage)
{
return new Result(State.ERROR, errorMessage);
}
public boolean isOK()
{
return (this.state == State.OK);
}
public String getErrorMessage()
{
return errorMessage;
}
}
The client code then looks like this:
Result result = Result.ok();
Result result = Result.error("Could not ...");
if (result.isOK())
...
else
{
String errorMessage = result.getErrorMessage();
...
}
This has the benefit that when creating a result, the client only has to deal with error messages in case of an error.
On the other hand, the API does not prevent the client code to ask for an error message in case of an OK result. That does not feel right.
I also don't like the way the information about valid states (OK/ERROR) gets dupplicated into:
- the internal enumeration,
- the public static methods.
What do you think about my implementation? How would you design the class?