I find myself constantly writing this statement
MyObject myObject = something.getThatObject();
if( myObject !=null &&
myObject .someBooleanFunction()){
}
in order to prevent a null pointer exception. Is there a shortcut to this in Java? I'm thinking like myObject..someBooleanFunction()
?
In Java 8:
static <T> boolean notNull(Supplier<T> getter, Predicate<T> tester) {
T x = getter.get();
return x != null && tester.test(x);
}
if (notNull(something::getThatObject, MyObject::someBooleanFunction)) {
...
}
If this style is new to the readers, one should keep in mind, that full functional programming is a bit nicer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With