Avoid if for chained objects [duplicate] - java

This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 2 years ago.
I have one complex object just like this;
Object A
Object B
Object C
Object D
property A
property B
So If I need to show the property A in my view, I need to
A.getB().getC().getD().getPropertyA();
but what if my user doesn`t send the object C?
so I need to create one If for every object
if(A.getB() != null){
if(A.getB().getC() != null){
if(A.getB().getC().getD() != null){
//here I can show the propertyA
}
}
}
now I have to show this property in 3 views
There is a better way to does this? a framework or something like this to solve this problem?

You can use Optional.ofNullable and map:
Optional.ofNullable(A.GetB())
.map(B::getC)
.map(C::getD)
.map(D::getPropertyA)
.orElseThrow()
P.S.1: Some developers (and linters) find this approach a code smell, but I think it's more readable that way.
P.S.2: You can use a default value with .orElse instead of .orElseThrow.

Related

Best way to check null for each part of an experssion in java [duplicate]

This question already has answers here:
Check chains of "get" calls for null
(11 answers)
Closed 1 year ago.
So I have something that looks like this:
(String) loginResponse.getGroup().getAdditionalProperties().get(something);
and each and every component of the expression could return null. I want to avoid throwing an exception and checking if null after each call doesn't look like the best way to do it:
temp= loginResponse.getGroup();
if(temp!=null){
temp= temp.getAdditionalProperties()
if(temp!=null){
temp.get(something)
}
}etc...
What's a better way to do this?
Thanks
you can use "Optional" and chain the call inside a map()
Optional.ofNullable(toto).map(A::getB).map(B::getC).orElseThrow(...)
Optional.ofNullable(toto).map(A::getB).map(B::getC).orElseGet(...)
You avoid nullPointerException by this way. It goes in the orElse... if anly element is null at any places

Null pointer exception inside Optional.ofNullable() [duplicate]

This question already has answers here:
How to convert Optional<Object> to Optional<String> [closed]
(3 answers)
Closed 2 years ago.
I am trying to convert a set to string inside Optional.OfNullable method like:
test.setAbc(Optional.ofNullable(rule.getSampleSet().toString()).orElse(null));
but if sampleSet is null it will give me a NullPointerException.
can anyone tell me how to resolve this issue using .map method with Optional?
I know one traditional way of doing it by checking nullability beforehand:
if(rule.getSampeSet != null)
but I am much interested in knowing if we can do it in one line.
Instead of calling toString() inside the ofNullable, you could map the optional to it:
test.setAbc(Optional.ofNullable(rule.getSampleSet()).map(Object::toString).orElse(null));

Avoiding null check when accessing an object property in java [duplicate]

This question already has answers here:
Null check in Java 8 Elvis operator?
(2 answers)
Closed 5 years ago.
I have a situation where I need get the property of a Java object if the object exists or null.
Something like foo == null ? null : foo.bar
Is there an operator available in java to do the same?
No, there is no propagate null operator in Java, cf. C# for example, which does have one. (It was a proposal at some point in Java's evolution, but has not sadly yet been incorporated into the language: foo = foo?.bar would be an obvious notation.)
You need to write this out longhand, as you have done.

local variable or repeated calls? [duplicate]

This question already has answers here:
Java optimization : local variable or function call
(5 answers)
Closed 6 years ago.
I have a very basic question. Which if the below 2 is better performance-wise:
if (getSomeValue() != null) {
processSomeValue(getSomeValue());
}
OR
String someValue = getSomeValue();
if (someValue != null) {
processSomeValue(someValue);
}
getSomeValue() is a normal getter which does not do anything else.
A best practice is to always use the 2nd way even you already know that the getSomeValue() is a simple getter. The key thing is that the call might be maintained in the future and changed by someone in the future. Any developer if change the inner code of getSomeValue() may not be aware of the invocation method that you are currently using.

When sent to a constructor in Java, what does "null" value do? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Which constructor is chosen when passing null?
I recently came across this curiosity while coding a few days back and can't seem to figure out why the following happens:
Given the class below
public class RandomObject{
public RandomObject(Object o){
System.out.println(1);
}
public RandomObject(String[] s){
System.out.println(2);
}
}
When the call new RandomObject(null); is made the output is always 2 regardless of the order in which the constructors were created. Why does null refer to the string array rather than the object?
The key here is that Object is the super type of String[]
Java uses the most specific available method to resolve such cases. Null can be passed to both methods without compilation errors so Java has to find the most specific method here. The version with String[] is more specific - therefore it will be chosen for execution.
Someone else has had this question earlier, check this post
If there are two cases to choose from, the compiler will first try to pick the more specific case. In this case, String will be picked over Object.
In the other question it was String str instead of String[] s
Thus, since String[] is a more specific datatype than its super type Object, it is picked.

Categories

Resources