Sujatha
Sujatha

Reputation: 3

How to refactor this Enum in java

I have a enum to hold the outcome of a rule:

enum Outcome{
    PASSED,
    FAILED;
}

Now I need to add reasons why the rule failed to the Outcome I return. How can I refactor this?

Upvotes: 0

Views: 1119

Answers (2)

geneSummons
geneSummons

Reputation: 925

If the "Outcome" you return must be an enum Type and you know at compile time all the reasons why failure might occur, then you can define a failure token for each type. For dynamic failure messages, failure reasons that can only be known at run time, I would go with Jay Schauer / JBNizet's comment-solution and make a separate class with members for the pass/fail token and the message string.

enum Outcome {
    PASS("Congratulations"),
    FAIL_BLANK("too many blank stares"),
    FAIL_RED("too many Red Herrings"),
    FAIL_NET("network issues");

    private String msg;
    private Outcome(String message) {
       msg = message;
    }

    public String getMsg() { return msg; }
}

Upvotes: 1

Jay Schauer
Jay Schauer

Reputation: 487

EDIT: I like @JBNizet 's answer better, so here is an implementation

public class Outcome {
    public enum OutcomeOptions {
        PASSED, FAILED;
    }
    private final OutcomeOptions outcome;
    private final String message;
    public Outcome(OutcomeOptions outcome, String message) {
        this.outcome = outcome;
        this.message = message;
    }
    public OutcomeOptions getOutcome() {
        return outcome;
    }
    public String getMessage() {
        return message;
    }
}

Upvotes: 1

Related Questions