Video in progress

Strong Middle 🧱 OOP and SOLID

How can you get rid of `switch`es by adding behavior to an enum, and where is the limit?

Enum constants can have their own method implementations (a constant-specific body) or take a lambda/value through the constructor. Then each state's behavior sits next to the constant, and the switch isn't repeated. But putting infrastructure dependencies into an enum is a mistake.

📖 Answer

public enum Tariff {
    MONTHLY(31) {
        @Override Money price(Money base) { return base; }
    },
    YEARLY(366) {
        @Override Money price(Money base) { return base.times(12).percentOff(20); }
    };

    private final int days;
    Tariff(int days) { this.days = days; }

    public Instant expiresFrom(Instant start) { return start.plus(Duration.ofDays(days)); }
    abstract Money price(Money base);
}

Now it is just tariff.price(base), and you don't write switch (tariff) in five places in the code. If a new QUARTERLY is added, the compiler forces you to implement price().

A shorter variant, a lambda in the constructor:

enum Op {
    PLUS((a, b) -> a + b), MINUS((a, b) -> a - b);
    private final IntBinaryOperator f;
    Op(IntBinaryOperator f) { this.f = f; }
    int apply(int a, int b) { return f.applyAsInt(a, b); }
}

The limits:

  • an enum is a singleton, and you can't inject a Spring bean, repository or HTTP client into it. If the behavior needs an external resource, do it with a Map<Tariff, PricingStrategy> of beans;
  • if the behavior depends on a layer (a color in the UI, a report format), don't put it in the domain enum; a switch in that layer is fine, and in Java 21 it is safe thanks to the exhaustiveness check;
  • in an enum with constant bodies, Tariff.YEARLY.getClass() is no longer Tariff but an anonymous subclass, so use getDeclaringClass().