ben-manes / caffeine

A high performance caching library for Java
Apache License 2.0
15.88k stars 1.6k forks source link

[Feature] Annotation driven caching #1796

Open abhiandthetruth opened 12 hours ago

abhiandthetruth commented 12 hours ago

do you think having an annotation that automagically caches a methods results against the arguments as key makes sense?

I tried to implement this in my service, was not able to build rigid type checks etc with Java generics else it kinda worked. The technical feasibility parked, do you think the annotation makes sense?

@ben-manes

ben-manes commented 4 hours ago

That feature is often provided by other frameworks like Spring, Quarkus, Micronaut, and JCache. There are custom versions, like JetCache, so the idea is relatively popular. Caffeine has a JSR-107 JCache adapter to use their standardized set, but it is not recommended because JCache was abandoned, was never popular, and has many design flaws. Since frameworks may provide this as part of their programming model, I don't think its desirable for us to provide our own ad hoc ones.

In my work projects, my personal taste is to not use annotation-driven caching and use the api directly. I consider caching to be a class implementation detail rather than its API, as I might need to perform pre/post processing before calling the cache. Then if I have to refactor the caching logic into a separate class to abide by some AOP proxying rules, the business logic becomes harder to follow as its semi randomly scattered across classes and methods. This is the classic problem of coupling and cohesion. The annotation driven caching does not improve decoupling as its not needed for the class API and I am unlikely to swap the vendor, and it reduces cohesion as the code is harder to follow and more complex since it may need to reinvent features available only in the cache interface api. So I avoid it due to a lack of an obvious benefit, but I am not opposed if others find it useful for their scenarios.