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.
Related
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
I have a Spring JPA search criteria like below. Where area is an Integer.
cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.
Two cleaner solutions come to my mind:
using Optionals e.g. `Optional.ofNullable(searchConstraint.getAreaMax()).orElse(Integer.MAX_VALUE)
areaMin and areaMax should have sensible default values which are overwritten only if user provided some data ; the data itself should be validated
if getAreaMin and getAreaMax are NULL you can avoid/ignore to add this criteria .
if getAreaMin is NULL and getAreaMax is NOT NULL you can use le() instead of between , and the same for getAreaMax with gt() method;
'if' code is ok.
something like this :
if(isNotNull(searchConstraint.getAreaMin()) && isNotNull(searchConstraint.getAreaMax())) {
cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
}else{
if(isNotNull(searchConstraint.getAreaMin()){
cb.gt(root.get(Property_.area), searchConstraint.getAreaMin());
}else{
cb.le(root.get(Property_.area), searchConstraint.getAreaMax());
}
}
Or you can create a util method like (but the prev variant is better dut to performance issue):
private Integer getValueOrDefault(Integer value , Integer defaultValue){
return value==null ? defaultValue : value;
}
execute :
cb.between(root.get(Property_.area), getValueOrDefault(searchConstraint.getAreaMin(), Integer.MIN_VALUE), getValueOrDefault(searchConstraint.getAreaMax(), Integer.MAX_VALUE))
If both values can be null I'd suggest splitting the between query into two predicates and then combining them. This way you can also handle the case when both of them are null:
List<Predicate> predicates = new ArrayList<>();
if (searchConstraint.getAreaMin() != null)
predicates.add(cb.gt(root.get(Property_.area), searchConstraint.getAreaMin()))
if (searchConstraint.getAreaMax() != null)
predicates.add(cb.lt(root.get(Property_.area), searchConstraint.getAreaMax()))
if (predicates.size() > 0)
cb.and(predicates.toArray(new Predicate[predicates.size()]))
How can i rewrite this:
private Comparator<Domain> byRank;
...
byRank = new Comparator<Domain>() {
#Override
public int compare(Domain d1, Domain d2) {
float tmp1 = d1.getDomainRank() == null ? 0 : d1.getDomainRank();
float tmp2 = d2.getDomainRank() == null ? 0 : d2.getDomainRank();
return Float.compare(tmp1, tmp2);
}
};
into lambda?
According to check null value before sorting using lambda expression, I tried this:
byRank = Comparator.nullsFirst(Comparator.comparing(Domain::getDomainRank));
However, it fails with:
java.lang.NullPointerException: null
at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
at java.util.Comparators$NullComparator.compare(Comparators.java:83)
at java.util.PriorityQueue.siftUpUsingComparator(PriorityQueue.java:669)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:645)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)
Edit: the lambda fails even if I check compared objects for null before comparison:
Queue<Domain> topByRank = new PriorityQueue<>(TOP, byRank);
...
for (Domain domain : domains) {
if (domain == null) { // check here
continue;
}
topByRank.add(domain); // here it fails
}
It should be:
Comparator.comparing(Domain::getDomainRank,
Comparator.nullsFirst(Comparator.naturalOrder()))
So we sort a list based on domainRank. But what are we going to do with Domain objects whose domainRank value is null? We going to keep them at the head of our collection:
Comparator.nullsFirst(Comparator.naturalOrder())
Your code will put null Domains first. If you want to check for null rank, you need to use this:
Comparator.comparing(Domain::getDomainRank, Comparator.nullsFirst(Comparator.naturalOrder()))
But keep in mind that this is only equivalent to your original comparator if the rank can't be less than 0. Otherwise, you'll have to test a similar expression:
Comparator.comparing(d -> d.getDomainRank() == null ? 0 : d.getDomainRank())
Alternatively, you might have meant to use Float.MIN_VALUE instead of 0 in your original code.
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.
Consider the following Code Snippet:
if (foo != null
&& foo.bar != null
&& foo.bar.boo != null
&& foo.bar.boo.far != null)
{
doSomething (foo.bar.boo.far);
}
My question is simple: is there a more simple\shorter way to do this ?
In detail: is there a more simple way to validate each part of the chain, I'd imagine similar to this ..
if (validate("foo.bar.boo.far"))
{
doSomething (foo.bar.boo.far);
}
Maybe like that ?
if (FooUtils.isFarNotEmpty(foo)){
doSomething (foo.bar.boo.far);
}
and in FooUtils :
boolean isFarNotEmpty (Foo foo){
return foo != null &&
foo.bar != null &&
foo.bar.boo != null &&
foo.bar.boo.far != null;
}
In my opinion this expression is perfect, nothing can be simpler
why you are using public instance variable, encapsulate your public variables and create getter and setter for them and you can perform these check in your getter, and you can return new Object() if any of them is null, or you can run this statement in try-catch block but not recommended,
If this is your API please consider some advice.
"I call it my billion-dollar mistake." - Sir C. A. R. Hoare, on his
invention of the null reference
There's not much you can do with this, unfortunately. If you ask me, it's a problem with the Java language. Groovy has something called the Safe Navigation Operator ?. that is specifically for this purpose. Here are two things I've done in the past.
The answer that Grisha already gave, so I won't repeat it
Naively wrote code that accesses it, and surround it in a try/catch for a NPE. Here's an example:
try {
if (foo.bar.boo.far != null) {
//do something
}
} catch (NullPointerException e) {
//do what you would do in an else
}
I don't particularly like the 2nd option, but I say if it actually makes the code cleaner, consider using it.
One time I was working with a library that is a very thin wrapper over an XML schema and I decided to use the 2nd option for this case. If I didn't, the code would have been harder to maintain because it would be so easy to forget a null check and they cluttered up the important logic. I think that's a valid case for using it.
Please try this code
try {
if (foo.bar.boo.far != null) {
//No object is null
}
} catch (Exception e) {
// some object is null and causes null point exception.
}