diff --git a/src/main/java/com/fewlaps/quitnowcache/QNCache.java b/src/main/java/com/fewlaps/quitnowcache/QNCache.java index 28f69ee..0241edb 100644 --- a/src/main/java/com/fewlaps/quitnowcache/QNCache.java +++ b/src/main/java/com/fewlaps/quitnowcache/QNCache.java @@ -97,6 +97,18 @@ public T get(String key) { } } + /** + * Gets an element from the cache. If it's null, the default value will be returned instead. + */ + public T getOrDefault(String key, T defaultValue) { + T value = get(key); + if (value == null) { + return defaultValue; + } else { + return value; + } + } + /** * Gets an element from the cache. If the element exists but it's dead, * it will be removed from the cache to free memory. It could call diff --git a/src/test/java/com/fewlaps/quitnowcache/GetOrDefaultTest.java b/src/test/java/com/fewlaps/quitnowcache/GetOrDefaultTest.java new file mode 100644 index 0000000..d2970ce --- /dev/null +++ b/src/test/java/com/fewlaps/quitnowcache/GetOrDefaultTest.java @@ -0,0 +1,34 @@ +package com.fewlaps.quitnowcache; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class GetOrDefaultTest extends BaseTest { + + QNCache cache; + + @Before + public void init() { + cache = new QNCacheBuilder().createQNCache(); + } + + @Test + public void valueIsReturnedIfItsPresent() { + cache.set(A_KEY, A_VALUE, ONE_SECOND); + + String result = cache.getOrDefault(A_KEY, "nothing"); + + assertEquals(A_VALUE, result); + } + + @Test + public void defaultIsReturnedIfValueIsNotPresent() { + cache.remove(A_KEY); + + String result = cache.getOrDefault(A_KEY, "nothing"); + + assertEquals("nothing", result); + } +}