I was making a simple currency converter utility and had to cache the conversion factors after fetching from server. Came up with the below interface. I have basically delegated the caching responsibility to OkHttp itself. Review appreciated.

public interface CurrencyConverter {

    Interceptor CACHE_CONTROL_INTERCEPTOR = chain -> chain.proceed(chain.request())
                                                          .header("Cache-Control", String.format("max-age=%d, max-stale=%d", 3600, 0))

    OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .cache(new Cache(new File(System.getProperty("java.io.tmpdir")), 1024 * 1024 * 10))

    BigDecimal getConversionFactor(String currencyFrom, String currencyTo) throws IOException;

    BigDecimal convert(String currencyFrom, String currencyTo, BigDecimal value) throws IOException;

The server is 3rd party and sends a no-cache header which I think does not make sense. It should be safe to cache conversion factors for some duration.


1 Answer 1


It makes perfectly sense to make that not cachable. You want the result based on the actual exchange rate, and this changes every second.

What I really don't like: Your interface has a HttpClient and is therefore coupled to implementation. This should be moved to the actualy implementation.

The next thing: You're caching is also coupled to the technology. So if the backend changes, let's say you get it from a database, the caching mechanism is not reusable. I think it's okay for your case, and I wouldn't bother too much,... but, if you consider testing, you actually can't unit test the caching.

  • \$\begingroup\$ Good points, can't really argue there. Thanks for the feedback ! \$\endgroup\$
    – Dexter
    Apr 21, 2017 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.