Video in progress

Strong Middle 🌊 Streams and lambdas

When is choosing a strategy with a Map<Key, Function> instead of a big if/else or switch a good idea, and when is it bad?

If there are many strategies and they get added at runtime or from configuration, Map<Type, Function> (EnumMap for an enum) is convenient. But in Java 21 a sealed type and switch make the compiler check all cases, while in a map a forgotten key only shows up at runtime as a null.

📖 Answer

A commission calculation example:

enum PaymentType { CARD, CASH, TRANSFER }

private static final Map<PaymentType, Function<BigDecimal, BigDecimal>> FEES =
        new EnumMap<>(Map.of(
                PaymentType.CARD,     a -> a.multiply(new BigDecimal("0.01")),
                PaymentType.CASH,     a -> BigDecimal.ZERO,
                PaymentType.TRANSFER, a -> new BigDecimal("2000")));

BigDecimal fee(PaymentType type, BigDecimal amount) {
    var rule = FEES.get(type);
    if (rule == null) throw new IllegalStateException("Komissiya qoidasi yo'q: " + type);
    return rule.apply(amount);
}

When this is good:

  • the rules come as Spring beans: Spring injects a Map<String, FeeRule> itself, keyed by bean names;
  • plugin style: to add a new type you don't touch existing code;
  • the table form is easy to read and you can swap a single rule in a test.

When it's bad: a new PaymentType.CRYPTO is added, but adding it to the map is forgotten. The compiler stays silent, and the bug shows up in prod. With switch:

BigDecimal fee(PaymentType type, BigDecimal a) {
    return switch (type) {                  // a new enum value is a compile error
        case CARD -> a.multiply(new BigDecimal("0.01"));
        case CASH -> BigDecimal.ZERO;
        case TRANSFER -> new BigDecimal("2000");
    };
}

My rule: if the cases form a closed set that lives inside the code, use switch (sealed or enum). For an open set, with rules registered from outside, use a map. If you choose a map, add a small test or a @PostConstruct check that verifies every key is present when the application starts.