I want to set an Integer to a specific value, which is 0 or the attribute found in another class. Since instances of this class are stored in a Map of Lists, but this map may be null at the point, I wonder which of the both ways to handle this are better.
Integer value = 0;
if (myMap != null &&
myMap.get(keyForList) != null &&
myMap.get(keyForList).get(0) != null) {
value = myMap.get(keyForList).get(0).getAttribute();
}
Or the way which I would consider better and more efficient:
Integer value = 0;
try {
value = myMap.get(keyForList).get(0).getAttribute();
} catch (NullPointerException e) {
// without doing anything value is 0 as expected
}
Thanks for any help!
The standard advice is that exceptions shouldn’t be used for flow control. They’re relatively heavy-weight, break the standard flow of control and consequently can be difficult to follow. They should be used for exceptional circumstances.
That’s not to say that you can’t use them to recover from conditions, but if it’s easy/more explicit to check for (say)
nullor zero, then you should do that in preference.I would note (however) that Java is verbose and doesn’t have simple operations for handling defaults/nulls in code such as:
As such, my advice is:
aitself to getb, and objectbwould getc, and so on. In it’s current form it breaks the Law of Demeter and exposes to you howa,b,cetc are composed. Remember that OO is about getting objects to do things for you, not having them tell you what they’re composed of and having you do it yourself.