For my last project I needed some kind of cache. I had one web service providing the main functionality and that was using another service for session and user information. Having each web request triggering multiple requests internally to resolve user and session data was not an option. In pharo there is a class called LRUCache. It is like a dictionary where the only implemented method is #at: .
The LRUCache is created by providing a size of the dictionary and a factory block. When an element is requested by using at: the factory block will be invoked if the element is not present. LRUCache does not give you control over the storage of the elements. Either it is there or it will be created and exists then. For my user and session data the situation was slightly more complicated. I don’t want to store user information when the user is not confirmed (it can change within the next seconds if the user confirms). And sessions should be removed from the dictionary if they are expired. The removal of expired sessions is not necessary as they would be sorted out automatically. It is an optimization because the cache will be less efficent if expired session block upper position in the LRU order until the reach the tail of the list and get discarded.
To serve my purpose I created a LRUDictionary class. It works like the LRUCache class (yes, I preserved the nice statistics the LRUCache provides about its usage) but adds more of the dictionary protocol to it. I added
at:ifAbsent: at:ifAbsentPut: at:ifPresent: at:put: removeAt: removeKey: removeKey:ifAbsent
The code can be found on smalltalkhub.Feel free to improve, comment or criticize