Skip to content

Commit

Permalink
Add getOrDefault() method
Browse files Browse the repository at this point in the history
  • Loading branch information
rocboronat committed Jul 28, 2018
1 parent 08abe5c commit 4bba78f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/main/java/com/fewlaps/quitnowcache/QNCache.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions src/test/java/com/fewlaps/quitnowcache/GetOrDefaultTest.java
Original file line number Diff line number Diff line change
@@ -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<String> 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);
}
}

0 comments on commit 4bba78f

Please sign in to comment.