Re: Enum Idiom Question
Rhino a ?crit :
I would seriously consider instead of the enum to have a boolean
plus a String, because true/false and a textual explanation is
really what you need.
Sorry, I meant to comment on this point too and didn't realize I had missed
it right away....
My little PadResult class started out with a boolean and a string with the
boolean indicating success or failure of the method and the string
containing either an error message or the padded version of the input
string. But when I looked at the invocation of PadResult and saw
PadResult padResult = new PadResult(true, paddedString);
or
PadResult padResult = new PadResult(false, errorMsg);
I found myself a bit challenged to remember if "true" meant "true, the
method produced a good result" or "true, the method found an error". I could
probably just memorize that true means a successful result or use some
boolean constants to make it clearer - see the example below - but I thought
it would be clearer still if I used a well-named enum value so I went with
the enum.
When a constructor's argument are not sufficiently clear, it might be a
good idea to use a factory method instead:
public class PadResult {
private String result;
private String errorMessage;
private boolean successful;
private PadResult(boolean successful, String resultOrErrorMessage) {
this.successful = successful;
if (successful) {
this.result = resultOrErrorMessage;
}
else {
this.errorMessage = resultOrErrorMessage;
}
}
public static PadResult createSuccessfulResult(String result) {
return new PadResult(true, result);
}
public static PadResult createFailedResult(String errorMessage) {
return new PadResult(false, errorMessage);
}
// getters omitted
}
then your pad() method uses
return PadResult.createSuccessfulResult(result);
or
return PadResult.createFailedResult(errorMessage);
and it's much clearer.
JB.