For methods where ...
- there exists a static one-to-one mapping between the input and the output, and
- the cost of creating the output object is relatively high, and
- the method is called repeatedly with the same input
... there is a need for caching result values.
In my code the following result value caching pattern is repeated a lot (pseudo-code in Java, but the question is language-agnostic):
private static Map<Input, Output> fooResultMap = new HashMap<Input, Output>();
public getFoo(Input input) {
if (fooResultMap.get(input) != null) {
return fooResultMap.get(input);
}
Output output = null;
// Some code to obtain the object since we don't have it in the cache.
fooResultMap.put(input, output);
return output;
}
Repeating this structure all the time is a clear violation of the DRY principle.
Ideally, I'd like the code above to be reduced to the following:
@CacheResult
public getFoo(Input input) {
Output output = null;
// Some code to obtain the object since we don't have it in the cache.
return output;
}
Where the theoretical CacheResult annotation would take care of the caching I'm currently doing by hand.
The general term for this type of caching is "memoization".
A good example of the exact functionality I'm looking for is Perl core module "Memoize".
In which languages does such a Memoize-like caching solution exist (either at the language level or the library level)? In particular - does such a solution exist for any major platform such as Java or .NET?