I'm sorry for the title but I cant find a good way to describe the problem in one sentence. In short, I have a lot of Java code following this pattern
if (obj != null && obj.getPropertyX() != null) {
return obj.getPropertyX();
}
return defaultProperty;
which can be rewritten as
return obj != null && obj.getPropertyX() != null ? obj.getPropertyX() : defaultProperty;
It's still ugly and I'm wondering if there is some API in Google Guava or other library to help clean up this code. Specifically, I'm looking for something like
return someAPI(obj, "getPropertyX", defaultProperty);
I can implement this method using reflection but I'm not sure if that's the proper way to do it. Thanks.
Null-safe operator is a new syntax in PHP 8.0, that provides optional chaining feature to PHP. The null-safe operator allows reading the value of property and method return value chaining, where the null-safe operator short-circuits the retrieval if the value is null , without causing any errors.
In certain computer programming languages, the Elvis operator, often written ?: , or or || , is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. This is identical to a short-circuit or with "last value" semantics.
The Angular safe navigation operator, ? , guards against null and undefined values in property paths. Here, it protects against a view render failure if item is null .
It is used to avoid sequential explicit null checks and assignments and replace them with method/property chaining.
In Java 8, you could use:
return Optional.ofNullable(obj).map(Obj::getPropertyX).orElse(defaultProperty);
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