try..catch VS long if() [duplicate] - java

This question already has answers here:
Null check chain vs catching NullPointerException
(19 answers)
Closed 6 years ago.
I have a complex model structure in my project.
Sometimes I have to get a deep placed value from it. It looks like following:
something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
The problem is that each of those methods could return null, and I will get NullPointerException in case if it does.
What I want to know is should I write long if like
if(something != null && something.getSomethongElse() != null && something..getSomethongElse().getSecondSomething() != null && something.getSomethongElse().getSecondSomething().getThirdSomething() != null && omething.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething() != null) {
//process getFourthSomething result.
}
Or it is OK just to use try..catch like following:
SomethingFourth fourth = null;
try {
fourth = something.getSomethongElse().getSecondSomething().getThirdSomething().getFourthSomething();
} catch (NullPointerException e) { }
if(fourth != null) {
///work with fourth
}
I know that NPE is a thing to be avoided, but isn't it overhead to avoid it in my case?

If you can refactor the code and make each method return Optional. It will be possible to avoid null checks and try ... catch.
Optional<Result> result = something.getSomethingElse()
.flatMap(e -> e.getSecondSomething())
.flatMap(x -> x.getThirdSomething())
.flatMap(e -> e.getFourthSomething());
// at the end to check if result is present
result.ifPresent(..some_logic_here..); // or result.orElse(...);
so getSomethingElse() returns Optional<SomethingElse>, getThirdSomething() - Optional<ThirdSomething> and so on. We have to use here flatMap(Function<? super T,Optional<U>> mapper) because if the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with an additional Optional. In other words if map on map(e -> e.getSecondSomething()) the result type will be Optional<Optional<SecondSomething>> and we will have to do unnecessary get() call - map(...).get().map(...).
I hope this helps.
UPDATED
You can do the same thing using method references.
Optional<Result> result = something.getSomethongElse()
.flatMap(SomethongElse::getSecondSomething)
.flatMap(SecondSomething::getThirdSomething)
.flatMap(ThirdSomething::getFourthSomething);

Related

Sort a Java collection object based on one field in it and apply checks

retList.sort((comp1, comp2) ->
compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment())));
I want to add a null check before comparing. How can I do that?
retList.sort((comp1, comp2) ->
if(compartmentOrderMap.get(comp2.getCompartment()) != null && compartmentOrderMap.get(comp1.getCompartment()) != null)
compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment()));
);
//I want to do something like this
Your operation
retList.sort((comp1, comp2) ->
compartmentOrderMap.get(comp2.getCompartment())
.compareTo(compartmentOrderMap.get(comp1.getCompartment())));
is equivalent to
retList.sort(Comparator.comparing(
c -> compartmentOrderMap.get(c.getCompartment()),
Comparator.reverseOrder()));
With this factory based form, you can easily replace the value comparator with a null safe variant, e.g.
retList.sort(Comparator.comparing(
c -> compartmentOrderMap.get(c.getCompartment()),
Comparator.nullsFirst(Comparator.reverseOrder())));
You have to decide for a policy. Instead of nullsFirst you can also use nullsLast.
you have to put {} inside the lambda for multiple line code:
retList.sort((comp1, comp2) -> {
if(compartmentOrderMap.get(comp2.getCompartment()) != null && compartmentOrderMap.get(comp1.getCompartment()) != null)
return compartmentOrderMap.get(comp2.getCompartment()).compareTo(compartmentOrderMap
.get(comp1.getCompartment()));
else
// throw a RuntimeException or return some integer value based on your logic
});
Use if/then/else to specify your needs. If you want all of this within one line, check the ternary operator on
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
It is explained including some examples here:
https://www.tutorialspoint.com/Java-Ternary-Operator-Examples

Using orElse() to return a default value [duplicate]

This question already has answers here:
Null check chain vs catching NullPointerException
(19 answers)
Check if last getter in method chain is not null
(3 answers)
Closed 5 years ago.
I have an object and i want to check if this object or nested fields are null. I want to print this neted field, but i should check if there is null in some level, otherwise i will get null pointer exception .
I know i can do this:
if( object != null && object.A != null && object.A.B != null && object.A.B.C != null && object.A.B.C.D != null) { doSomething( object.A.B.C.D);}
but its so long. Do you know better way to check it ?
Optional is a good way in Java 8.
String value = foo.getBar().getBaz().toString();
With optional it will be:
String value = Optional.ofNullable(foo)
.map(Foo::getBar)
.map(Bar::getBaz)
.map(Baz::toString)
.orElse("EmptyString");
You could implement an interface on all objects with method that returns all child objects and create a method that calls itself recursively to verify that all objects are set.
Let assume that this is a check to prevent misuse of a method, so this should not occurs too many time.
Simply catch this exception, this will invalidate the value.
private boolean isValid(YourObject object){
try{
return object.A.B.C.D != null;
} catch (NullPointerException npe){
return false;
}
}
Of course, don't use this solution if you are doing a lot of validation and those return false to often, exception are an heavy process.
EDIT :
As Fildor point it out, there is a cost to use a try-catch even without exception. But using this answer I can assume this will be limited and there is not much optimization to do on this unique line.

How to cleanly process java 8 stream "findFirst()" result even if empty

One area that I often finding confusing with java 8 streams is when an intermediate result can be empty, and you need to take alternate paths if it's empty or not empty.
For instance, if I have code like this:
String pymtRef = defaultValue;
Optional<PaymentTender> paymentTender = paymentTenders.stream()
.filter(pt -> (pt.getFlag() == Flag.N || pt.getFlag() == null)).findFirst();
if (paymentTender.isPresent()) {
pymtRef = paymentTender.get().getId();
}
return pymtRef;
I would like to figure out how to remove the conditional block and do this in a single stream.
If I simply call ".map" on the filter result, that can work if it found a matching entry. If not, I get a NoSuchElementException.
I might instead use "ifPresent()", but the return type of that is "void".
Is there any way to make this cleaner?
Update:
The solution using "orElse()" works fine.
The entire method now looks something like this:
public String getPaymentReference(OrderContext orderContext) {
List<PaymentTender> paymentTenders = getPaymentTenders(orderContext);
if (paymentTenders.size() == 1) {
return paymentTenders.get(0).getId();
}
return paymentTenders.stream()
.filter(pt -> (pt.getAutoBill() == AutoBill.N || pt.getAutoBill() == null))
.findFirst().map(pt -> pt.getId()).orElse(DEFAULT_VALUE);
}
Can you think of a way to include the first conditional in the stream without making it more complex?
Calling get() straight after map will yield an exception if the Optional has an empty state, instead call orElse after map and provide a default value:
paymentTenders.stream()
.filter(pt -> (pt.getFlag() == Flag.N || pt.getFlag() == null))
.findFirst()
.map(PaymentTender::getId)
.orElse(someDefaultValue);
Edit:
As for:
Can you think of a way to include the first conditional in the stream
without making it more complex?
No, this is better the way you've done it. it's more readable and easier to follow.
introducing any type of logic to make it into one pipeline (if possible) will just end of being complex and hence harder to follow and understand.
You can do it in one statement via
public String getPaymentReference(OrderContext orderContext) {
List<PaymentTender> paymentTenders = getPaymentTenders(orderContext);
return paymentTenders.stream()
.filter(paymentTenders.size() == 1? pt -> true:
pt -> pt.getAutoBill() == AutoBill.N || pt.getAutoBill() == null)
.findFirst().map(PaymentTender::getId).orElse(DEFAULT_VALUE);
}
Note that this will not repeat the evaluation of the paymentTenders.size() == 1 for every element, but use a different function, depending on the state. When the condition is fulfilled, pt -> true will accept any element, which will result in the sole element being accepted as intended. Otherwise, the ordinary predicate, pt -> pt.getAutoBill() == AutoBill.N || pt.getAutoBill() == null is used.

an elegant way to check for null

Working with hibernate I use this sort of code many times:
int someId = entity.getSomething() == null ? null : entity.getSomething().getId();
This code becomes a little more messy when trying to apply on a longer hierarchy:
int someId = entity.getParent() == null ? null :
entity.getParent().getParent() == null ? null :
entity.getParent().getParent().getSomething() == null ? null :
entity.getParent().getParent().getSomething().getId();
Is there a more elegant way to do it?
As per Louis Wasserman's comment, Optional can almost be used as a NullObject a'la flogy's solution.
Using Java 8 Optional and lambdas it looks like this
Integer value = Optional.ofNullable(entity)
.map( Entity::getParent )
.map( Entity::getParent )
.map( Entity::getSomething )
.map( Something::getId )
.orElse(null);
In case those entity objects are written by yourself and not in a library, I would consider refactoring them and use NullObjects. Like that you could then directly call
Integer someId = entity.getParent().getParent().getSomething().getId();
as this would then return your nulled integer.
Basically, it works like this:
entity.getParent() will return a NullParent instance
this NullParent class has a method getParent(), which also will return a NullParent instance
again, this NullParent class has a method getSomething(), which will return a NullSomething instance
the NullSomething class has a method getId(), which finally will return your nulled integer (e.g. 0 or another NullInteger object).
Here is an interesting post on Why NULL is bad?
Is there a more elegant way to do it?
You may simply go for try-catch for null check:
try{
int id = entity.getParent().getParent().getSomething().getId();
// do something with id
} catch(NullPointerException ex) {
// got null
}
You're assigning the same null value if it's null.
Why don't you try giving it only if it is not null.
if(x != null) x = y
Readability is very important factor as well as the simplification of code. It is better to use simple if condition here.
if(entity.getParent()!=null && entity.getParent().getParent() !=null &&
entity.getParent().getParent().getSomething()!=null &&
entity.getParent().getParent().getSomething().getId()!=null){
}
And because of &&("short-circuit and"), if one condition false non other condition in the right execute.

Best way to check for null values in Java?

Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.
What is the best way to go about this? I've considered these methods.
Which one is the best programming practice for Java?
// Method 1
if (foo != null) {
if (foo.bar()) {
etc...
}
}
// Method 2
if (foo != null ? foo.bar() : false) {
etc...
}
// Method 3
try {
if (foo.bar()) {
etc...
}
} catch (NullPointerException e) {
}
// Method 4 -- Would this work, or would it still call foo.bar()?
if (foo != null && foo.bar()) {
etc...
}
Method 4 is best.
if(foo != null && foo.bar()) {
someStuff();
}
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.
The last and the best one. i.e LOGICAL AND
if (foo != null && foo.bar()) {
etc...
}
Because in logical &&
it is not necessary to know what the right hand side is, the result must be false
Prefer to read :Java logical operator short-circuiting
Since java 8 you can use Objects.nonNull(Object obj)
if(nonNull(foo)){
//
}
Do not catch NullPointerException. That is a bad practice. It is better to ensure that the value is not null.
Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.
Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.
Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for.
Method 2 is just making it more complicated than it needs to be.
Method 1 is just method 4 with an extra line of code.
In Java 7, you can use Objects.requireNonNull().
Add an import of Objects class from java.util.
public class FooClass {
//...
public void acceptFoo(Foo obj) {
//If obj is null, NPE is thrown
Objects.requireNonNull(obj).bar(); //or better requireNonNull(obj, "obj is null");
}
//...
}
As others have said #4 is the best method when not using a library method. However you should always put null on the left side of the comparison to ensure you don't accidentally assign null to foo in case of typo. In that case the compiler will catch the mistake.
// You meant to do this
if(foo != null){
// But you made a typo like this which will always evaluate to true
if(foo = null)
// Do the comparison in this way
if(null != foo)
// So if you make the mistake in this way the compiler will catch it
if(null = foo){
// obviously the typo is less obvious when doing an equality comparison but it's a good habit either way
if(foo == null){
if(foo = null){
I would say method 4 is the most general idiom from the code that I've looked at. But this always feels a bit smelly to me. It assumes foo == null is the same as foo.bar() == false.
That doesn't always feel right to me.
Method 4 is my preferred method. The short circuit of the && operator makes the code the most readable. Method 3, Catching NullPointerException, is frowned upon most of the time when a simple null check would suffice.
Simple one line Code to check for null :
namVar == null ? codTdoForNul() : codTdoForFul();
Update
I created a java library(Maven Dependency) for the java developers to remove this NullPointerException Hell from their code.
Check out my repository.
NullUtil Repository
Generic Method to handle Null Values in Java
<script src="https://gist.github.com/rcvaram/f1a1b89193baa1de39121386d5f865bc.js"></script>
If that object is not null we are going to do the following things.
a. We can mutate the object (I)
b. We can return something(O) as output instead of mutating the object (I)
c. we can do both
In this case, We need to pass a function which needs to take the input param(I) which is our object If we take it like that, then we can mutate that object if we want. and also that function may be something (O).
If an object is null then we are going to do the following things
a. We may throw an exception in a customized way
b. We may return something.
In this case, the object is null so we need to supply the value or we may need to throw an exception.
I take two examples.
If I want to execute trim in a String then that string should not be null. In that case, we have to additionally check the null value otherwise we will get NullPointerException
public String trimValue(String s){
return s == null ? null : s.trim();
}
Another function which I want to set a new value to object if that object is not null otherwise I want to throw a runtime exception.
public void setTeacherAge(Teacher teacher, int age){
if (teacher != null){
teacher.setAge(age);
} else{
throw new RuntimeException("teacher is null")
}
}
With my Explanation, I have created a generic method that takes the value(value may be null), a function that will execute if the object is not null and another supplier function that will execute if the object is null.
GenericFunction
public <I, O> O setNullCheckExecutor(I value, Function<I, O> nonNullExecutor, Supplier<O> nullExecutor) {
return value != null ? nonNullExecutor.apply(value) : nullExecutor.get();
}
So after having this generic function, we can do as follow for the example methods
1.
//To Trim a value
String trimmedValue = setNullCheckExecutor(value, String::trim, () -> null);
Here, the nonNullExecutor Function is trim the value (Method Reference is used). nullExecutorFunction is will return null since It is an identity function.
2.
// mutate the object if not null otherwise throw a custom message runtime exception instead of NullPointerException
setNullCheckExecutor(teacher, teacher -> {
teacher.setAge(19);
return null;
}, () -> {
throw new RuntimeException("Teacher is null");
});
Correction: This is only true for C/C++ not for Java, sorry.
If at all you going to check with double equal "==" then check null with object ref like
if(null == obj)
instead of
if(obj == null)
because if you mistype single equal if(obj = null) it will return true (assigning object returns success (which is 'true' in value).
You also can use ObjectUtils.isNotEmpty() to check if an Object is not empty and not null.
If you control the API being called, consider using Guava's Optional class
More info here. Change your method to return an Optional<Boolean> instead of a Boolean.
This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional
if you do not have an access to the commons apache library, the following probably will work ok
if(null != foo && foo.bar()) {
//do something
}
Your last proposal is the best.
if (foo != null && foo.bar()) {
etc...
}
Because:
It is easier to read.
It is safe : foo.bar() will never be executed if foo == null.
It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code)
It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).
We can use Object.requireNonNull static method of Object class. Implementation is below
public void someMethod(SomeClass obj) {
Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}
public <T, U> U defaultGet(T supplier, Function<T, U> mapper, U defaultValue) {
return Optional.ofNullable(supplier).map(mapper).orElse(defaultValue);
}
You can create this function if you prefer function programming
Allot of times I look for null when processing a function -
public static void doSomething(Object nullOrNestedObject) {
if (nullOrNestedObject == null || nullOrNestedObject.getNestedObject()) {
log.warn("Invalid argument !" );
return;
// Or throw an exception
// throw new IllegalArgumentException("Invalid argument!");
}
nullOrNestedObject.getNestedObject().process()
... // Do other function stuff
}
That way if it is null it just stops execution early, and you don't have to nest all of your logic in an if.

Categories

Resources