Conversation
v2 and v1 dont have "ContainsOrAdd" but instead have "ContainsOrSet", as v2 and v1 don't have "Add" functions but v3 does.
There was a problem hiding this comment.
Thanks for the contribution! The overall approach is good — atomic check-and-add without external locking is a useful feature. A few things need to be addressed:
-
Expired item check missing — In all versions,
ContainsOrSet/ContainsOrAddchecksif _, ok := c.items[key]; okbut doesn't verify whether the item is expired. This means calling the method on an expired key would incorrectly return "contains=true" and skip the add, even though a subsequentGet()would return not-found. The check should also verify expiration, e.g.:if ent, ok := c.items[key]; ok { if !time.Now().After(ent.Value.(*cacheItem[K, V]).expiresAt) { return true, false } }
-
Test naming inconsistency — The test is named
TestCacheContainsOrAddin all versions, but v1 and v2 testContainsOrSet. The test names should match the method names being tested (TestCacheContainsOrSetfor v1/v2). -
Missing test cases:
- No test for expired key behaviour (calling the method on a key that exists but is expired — should treat it as not-present and add the new value)
- No test for TTL override in
ContainsOrSet(v1/v2) - No concurrency test for the new method
-
v1 interface change — Adding
ContainsOrSetto theCacheinterface in v1 is a breaking change for anyone who implements the interface externally. I would rather avoid it, maybe let's just add it to v3 if there is no way around it.
The naming split (v1/v2 use ContainsOrSet with TTL param, v3 uses ContainsOrAdd matching hashicorp's signature) makes sense given the API differences between versions — v3 has Add() while v1/v2 only have Set().
PR should hopefully address #17
Changes
ContainsOrAdd(key, value) (contains, evicted)in an attempt to match hashicorps ContainsOrAdd functionContainsOrSet(key, value, ttl) (contains)to V1 & V2 as they don't really have a concept of "Add" which returns a boolean if evicted like V3. Not sure about this part, let me know.Testing
All unit tests pass in V1, V2 & V3.