NullPointerException Utilities - Small but handy utilities to deal with annoying NullPointer Exceptions in Java applications.
Often you need to retrieve a value from your object model:
String sku = user.getOrder().getItem().getSku();
But of course, it is not guaranteed that all objects in the chain are always provided. Null pointer checks are necessary for your code to succeed.
So in order to retrieve the value, you would need to write code like this in Java:
String sku = "NA";
if (user != null &&
user.getOrder() != null &&
user.getOrder().getItem() != null) {
sku = user.getOrder().getItem().getSku();
}So much wrapping around of a simple requirement. With NPE Utils the code could look like so:
String sku = NpeUtils.npeSafe(
() -> user.getOrder().getItem().getSku(), "NA");
Another example:
List<String> collection = getCollection();
if (collection != null) {
for (String str: collection) {
System.out.println("string: " + str);
}
}
well, code above might fail misarably with a null pointer exception if your collection is null. So you could add null checks or use try catch blocks which again, adds a lot of null pointer exception hendling around your simple desire to iterate over a collection if it is not empty.
NpeUtils adds this level of convenience:
List<String> collection = null;
for (String str: NpeUtils.emptyIfNull(collection)) {
System.out.println("string: " + str);
}
This library covers some basic use cases. Please contribute if you have more ideas.
This library is a byproduct of Comunicatcha private instant messenger development.