For methods where ...
- there is a static one-to-one mapping between input and output and
- the cost of creating an output facility is relatively high, and
- the method is called multiple times with the same input
... there is a need to cache result values.
In my code, the result caching pattern is repeated many times (pseudo-code in Java, but the question is 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;
fooResultMap.put(input, output);
return output;
}
Repeating this structure all the time is a clear violation of the DRY principle.
Ideally, I would like the code above to be reduced to the following:
@CacheResult
public getFoo(Input input) {
Output output = null;
return output;
}
If the theoretical annotation CacheResult takes care of the caching, which I now do manually.
The general term for this type of caching is memoization . "
, , "Memoize" .
Memoize ( , )? - , Java .NET?