Video in progress

Strong Middle ☕ Core Java

When are constant-specific bodies for enum constants useful?

When each constant has to behave in its own way: for example, each commission type has its own formula. You declare an abstract method in the enum and each constant overrides it; if you add a new constant, the compiler asks for an implementation.

📖 Answer

In a lot of code you'll find a switch like this scattered around:

switch (type) {
    case CARD -> amount * 0.015;
    case P2P  -> 0;
    // WALLET was added, and this place was forgotten
}

You can move the logic into the enum:

public enum Fee {
    CARD {
        BigDecimal of(BigDecimal a) { return a.multiply(new BigDecimal("0.015")); }
    },
    P2P {
        BigDecimal of(BigDecimal a) { return BigDecimal.ZERO; }
    },
    WALLET {
        BigDecimal of(BigDecimal a) { return a.multiply(new BigDecimal("0.005")); }
    };

    abstract BigDecimal of(BigDecimal amount);
}

Now if a new constant doesn't write the method, the code doesn't compile.

Two subtle points:

  • each constant with a body is an anonymous subclass of the enum. Fee.CARD.getClass() returns Fee$1, while getDeclaringClass() returns Fee. Keep that in mind in places like Jackson or EnumMap;
  • passing a lambda to the constructor is another way: CARD(a -> a.multiply(...)). It's shorter, especially when the logic is one line.

When you don't need it: when the formula changes often or is configured from the DB. Then the enum is only an identifier, and the calculation lives in a separate service.