Writing a Key Value Store The purpose of this exercise is to write a basic key value store. It should use string keys and string values only. The following operations should be supported:
set get delete keys Function explanations
SET
Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its existence. The method should return the string "OK"
GET
Get the value of a key. If the key does not exist, return the string "nil"
DELETE
Removes the specified keys. A key is ignored if it does not exist. Returns the number of keys that were removed. This is a variadic function and should accept any number of keys as arguments.
delete("1","2") or delete("1") or delete("1","3","4"...)
delete(Object... arg) => arg behave as array.
public interface keyValueStore{
HashMap<String, String> map = HashMap<String,String>();
//performance of set ? O(1).
public String set (String key, String value) {
if (map.containsKey(key)) {
map.remove(key);
map.put(key,value);
} else {
map.put(key, value);
}
return "OK";
}
// find a way to diminish your code a little.
// get() => O(1)
public String get (String key) {
return map.get(key);
}
//delete("1","2")
//performance of delete ? O(n2)
// 100k max . delete 1 => (100k)
//clean your method.
public String delete (String... keys) {
if (keys == null || keys.length == 0)
return 0;
int count = 0;
for (String temp : keys) {
if (map.get(key) != null) {
map.remove(key);
count++;
}
}
return count;
}
}
advantage of interface:
We can have multiple implementation of one interface.
Interfaces are a way of decoupling separate software components. Sure, you may use an Oracle data base to store all your data today so why not dispense of all your DAO interfaces?
The answer is that strongly coupling to anything may come back and bite you in the future. What if next year you want to use some cloud service to store data? If you coded to a DAO interface you can simply introduce a new cloud implementation and plug it straight in. Your app is loosely coupled so doesn't need to change.