0

Firstly I assume that Java Enums should conform to the same practices as regular classes.

I'm a little hazy on the meaning of "Single responsibility". With the following code, I'm wondering if the hasSucceed method is the violation as it's logic goes beyond the purpose of holding the Level.

If it does violate the principle, how would I refactor?

package foo;

public enum Level {
    AWFUL(-4),
    TERRIBLE(-3),
    POOR(-2),
    MEDIOCRE(-1),
    FAIR(0),
    GOOD(1),
    GREAT(2),
    SUPERB(3),
    LEGENDARY(4);   

    private final int level;

    Level(int level) {
        this.level = level;
    }

    public int getValue() {
        return this.level;
    }

    public boolean hasSucceeded(Level requiredLevel, Level roll) {
        return getValue() + roll.getValue() >= requiredLevel.getValue();
    }
}
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
HedgepigMatt
  • 190
  • 3
  • 16

2 Answers2

3

You should think about reasons to change: do the requirements for hasSucceeded change for different reasons than the requirements for the list of levels? This cannot be judged based on the code alone, you need to think about the use cases. For example, if the levels enum is part of a library that is used for different game projects, it could cause problems if different games might want a different success logic.

Note that another principle, the principle of information hiding suggests that this method should be in this enum, because its arguments are also of type Level.

BTW, it is completely OK to treat enums as classes and add methods to them. This is one of the strengths of Java enums.

lbalazscs
  • 17,474
  • 7
  • 42
  • 50
  • +1 Developers shouldn't be afraid to utilize the power of java enums as classes, as long as they be consistent about it. – David Zech Aug 26 '15 at 20:32
2

I recommend you to leave the responsability of hasSuccessed method to another class which you can ask for this an others methods.

I prefer to put only the enums separated of the code or logic and use the Level enum as a "repository" of enums.

melli-182
  • 1,216
  • 3
  • 16
  • 29