If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)
Answer from AK4647 on Stack OverflowYour 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 a null 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 a null 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.
The idea is fine, really good in fact. Since Java 8 the Optional types exist, a detailed explanation can be found at Java Optional type. A example with what you posted is
Optional.ofNullable(country)
.map(Country::getTown)
.map(Town::Houses);
And further on.
You are not far, just map the value:
String strDouble = Optional.ofNullable(value).map(Objects::toString).orElse("not found");
Since the left side of the the assignment operator can be either a Double or a String, the best that can be done is to specify its type as Object.
This will work:
Object value2 = Optional.<Object>ofNullable(value).orElse("not found");
(i.e. The only shared class in the class hierarchy for Double and String is Object)
I used to think it'd be null, but then why would you explicitely initialize a variable to null in some cases?
Is it just garbage value?