Many times I find myself null checking when fetching a value from some data hierarchy to avoid NullPointerExceptions, which I find to be prone to errors and a needs a lot of boilerplate.
I've written a very simple routine which allows me to skip null checking when fetching an object…
public final class NoNPE {
public static <T> T get(NoNPEInterface<T> in) {
try {
return in.get();
} catch (NullPointerException e) {
return null;
}
}
public interface NoNPEInterface<T> {
T get();
}
}
I use it a bit like this…
Room room = NoNPE.get(() -> country.getTown().getHouses().get(0).getLivingRoom());
The above resulting in me getting a Room object or a null, without having to null check all parent levels.
What do you think of the above? Am I creating a problematic pattern? Is there a better way to do this in your opinion?
Best Answer
Your solution is very smart. The problem I see is the fact that you don't know why you got a
null
? Was it because the house had no rooms? Was it becuase the town had no houses? Was it because the country had no towns? Was it because there was anull
in the 0 position of the collection because of an error even when there are houses in positions 1 and greater?If you make extensibe use of the
NonPE
class, you will have serious debugging problems. I think it is better to know where exactly the chain is broken than to silently get anull
that could be hiding a deeper error.Also this violates the Law of Demeter:
country.getTown().getHouses().get(0).getLivingRoom()
. More often than not, violating some good principle makes you have to implement unorthodox solutions to solve the problem caused by violating such principle.My recommendation is that you use it with caution and try solve the design flaw that makes you have to incur in the train wreck antipattern (so you don't have to use
NonPE
everywhere). Otherwise you may have bugs that will be hard to detect.