Video in progress

Strong Middle 🧱 OOP and SOLID

How do you add caching, logging or retry to an existing class with a Decorator, without changing it?

You write a wrapper class that implements the same interface and holds the original object inside. It passes the call on to the original and does extra work before or after. You can wrap several decorators one after another.

📖 Answer

public interface RateProvider {
    BigDecimal rate(Currency from, Currency to);
}

class CbuRateProvider implements RateProvider { ... }   // HTTP call

class CachingRateProvider implements RateProvider {
    private final RateProvider delegate;
    private final Cache<String, BigDecimal> cache = Caffeine.newBuilder()
            .expireAfterWrite(Duration.ofMinutes(10)).build();

    CachingRateProvider(RateProvider delegate) { this.delegate = delegate; }

    public BigDecimal rate(Currency from, Currency to) {
        return cache.get(from + "-" + to, k -> delegate.rate(from, to));
    }
}

Assembling it in Spring:

@Bean
RateProvider rateProvider(CbuClient client, MeterRegistry m) {
    RateProvider p = new CbuRateProvider(client);
    p = new RetryingRateProvider(p, 3);
    p = new CachingRateProvider(p);      // the cache is outside: retry happens only on a miss
    return new TimedRateProvider(p, m);
}

The order matters: if the cache is outside the retry, the network isn't called at all on a cache hit.

What makes it better than inheritance:

  • CbuRateProvider doesn't change and doesn't know about the cache (SRP);
  • each behavior is tested on its own;
  • you assemble combinations in configuration, with no need for classes like CachingRetryingCbuRateProvider.

But if the interface has many methods, delegating all of them is tedious (Kotlin has by, Java doesn't). Self-invocation also doesn't go through the decorator: if the inner object calls its own method, the wrapper doesn't see it. Spring AOP proxies (@Cacheable, @Transactional) are exactly this decorator idea, and have the same limitation.