I have plenty of setters in my classes, as well as many methods to add an item or a set of items to lists or maps.
Should I check for nulls for each one of them, or should I allow NullPointerException
to happen? This is dangerous for maps though, since I could end up with null values and I wouldn't want that.
So basically, if I have this:
public void setMyMap(Map<Key, List<Value>> map) {
myMap = map;
}
public void addItem(Key k, Value v) {
if (map.containsKey(k))
map.get(k).add(v);
else
map.put(k, new ArrayList<Value>(Arrays.asList(v)));
}
public void addItems(Key k, List<Value> values) {
for (Value v : values) addItem(k, v);
}
Etc. Should I do this?:
public void setMyMap(Map<Key, List<Value>> map) {
if (map != null) myMap = map;
}
public void addItem(Key k, Value v) {
if (k == null || v == null)
return;
if (map.containsKey(k))
map.get(k).add(v);
else
map.put(k, new ArrayList<Value>(Arrays.asList(v)));
}
public void addItems(Key k, List<Value> values) {
if (k == null || values == null)
return;
for (Value v : values) addItem(k, v);
}
Side question: I am no fan of using return;
just as I did. Normally I would wrap the whole block in an if
statement checking if both are not null, rather that exiting the method earlier. Are both practices accepted? Which one should I rather do? Or it's just a matter of taste?
null
is passed. Instead, throw an exception, for example anIllegalArgumentException
. That will help users of your code quickly find out they are calling your method with an invalid value.