Is it possible to make Java code as groovy style - java

I'm trying to know whether we can write null check pointer in the same statement in Java, as we do in groovy? I've four places to check null. Can this be more simplified?
if(doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM") != null) {
if(doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) != null) {
Node searchResultNode = doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0);
if(searchResultNode != null) {
}
}
}
as
doc.getDocumentElement()?.getElementsByTagName("SEARCH-RESULT-ITEM")?.item(0)
Is it possible

You asked if it is possible to write Groovy-like code in a regular Java project. The simple answer is no.
However, the statement can be simplified by combining the null checks into one condition. In addition, if doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) is not null we don't need to check the local variable.
So we may end up with:
if (doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM") != null
&& doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0) != null {
Node searchResultNode = doc.getDocumentElement().getElementsByTagName("SEARCH-RESULT-ITEM").item(0);
}
Doing this reduces the number of IF statements from 3 to 1, and eliminates a redundant null check.

There is no safe dereference in Java.
It's generally bad practice to toss nulls around and Optional class may come to rescue as well ass checkNotNull at the beginning of the method, but nothing as fancy as Groovy one-liners.

Related

How to properly handle if statements containing both null checks and non-null checks together in an OR expression [duplicate]

This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed last month.
I have some code that does the following:
if(object == null || object.value.equals(" ")) {
// do something
}
else {
// do something else
}
The above seems dangerous to me because if I switched the order of the two conditions or changed this to an AND expression, the code will crash when object is null, but I also read somewhere that Java guarantees operands are evaluated from left to right. That said, I also read do not assume this to be true.
I am confused by all this conflicting advice and wondering whether the above code constitutes a bug. That said, what is the best way to recode this if indeed this is considered bad practice?
In Java && and || are short circuit (boolean!) operators. So everything works as assumed. No unnecessary evaluation running into an error. Some languages Name these and-then, or-else.
boolean newGraphRequired = graphNode == null
|| gaphNode.timeStamp() != moduleNode.timeStamp();
Conditions become more straightforward.
Use below piece of code -
if(object == null || (object != null && " ".equals(object.value))) {
// do something
}
else {
// do something else
}
Also Always keep constant values in left side of equals, it will prevent NPE.
For Above code if object is null or object.value is " "(space), it will go inside if otherwise it will go in else.

Java: Standards to use constant.equals(variable) [duplicate]

If I try to do a .equals() on a null string in java, a null pointer exception will be thrown. I am wondering, if I am trying to compare if a string is equal to some constant string, can I do the following:
MY_CONSTANT_STRING.equals(aStringVariable)
I know it will work, but is this just really poor code?
This is a standard Java idiom jokingly called a Yoda condition.
Personally I prefer to handle the null case explicitly, but the Yoda way is used a lot and any experienced Java programmer should be able to understand what is going on immediately. It's fine to use.
is this just really poor code?
No, this is the way many people would code the statement to avoid NPE.
What you've got is fine. It's even possible to use a String literal.
if( "value".equals(variable) ) {
...
If you don't like that, you can always explicitly check for null and equality, and combine the two checks with &&. The short circuiting of the operator will make sure you never get a NPE.
if( (variable != null) && variable.equals("value") ) {
...
I would keep the "CONSTANT.equals(possibleNull)" code without the null test only if it is a normal condition that the variable could be null - for instance because it just came out of a property map.
Similarly you can get away with not checking for null in instanceof-checks - like:
Food dinner = map.get("dinner");
if (dinner instanceof Soup) {
((Soup)blah).eat();
} // We don't care if it is a Fish or null
But if you really did not expect null, you should explicitly check for that in a separate if-test, and handle it appropriately. It's generally better to catch such data errors early rather than later.
Nope, it's usually done to avoid NPE. However, I usually prefer to do explicit check for null.
If you are concerned about the quality of your code, write a helper class that takes care of equality test:
public class ObjectHelper {
public static boolean testEquality(Object o1, Object o2) {
if (o1 == null && o2 == null) return true;
if (o1 == null) return false;
return o1.equals(o2);
}
}
Then use it like this:
if (ObjectHelper.testEquality(aStringVariable, My_CONSTANT_STRING))
Your so-called constant MIGHT stop being constant. It might be read from a configuration file some time in the future.

Java NullPointerException check on chained methods

I want to check for a null pointer when accessing a field several classes deep (in a chain of get methods). However, if one of the earlier methods is null I get a NullPointerException anyways.
This is what I want to check, though it can still get a NullPointerException:
if(x.getLocation().getBuilding().getSolidFuelInd() != null)
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
This the behavior I want the above code to exhibit:
if(x.getLocation() != null)
if(x.getLocation().getBuilding() != null)
if(x.getLocation().getBuilding().getSolidFuelInd() != null)
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
The field on the pol is optional and should only be set if the above getter is not null. However the building and location objects could also be null, so now I must check to that they're valid.
Is there any sort of shorter way to check all the above like I want?
With Java 8's Optional<> class, you can map a value as so:
Optional.of(x)
.map(ClassOfX::getLocation)
.map(Location::getBuilding)
.map(Building::getSolidFuelInd)
.map(solidFuelInd -> solidFuelInd ? "Y" : "N")
.ifPresent(pol::setWood_heat_ind);
map calls will only be executed if the value of the optional isn't null thus avoiding the NullPointerException.
ifPresent's purpose is to call your setWood_heat_ind only if a value if available.
A nice single-call equivalent to null checks.
If its code reduction you want then you can save each call in a variable.
// note: Replace type with the correct type
type location = x.getLocation();
type building = location == null ? null : location.getBuilding();
// note: you don't have to check for null on primitive types
pol.setWood_heat_ind(building != null && building.getSolidFuelInd() ? "Y" : "N");
This is much cleaner and easier to follow.
Food for thought, you don't check for null on primitive types boolean, int, byte etc. so the last null check on building.getSolidFuelInd() is not needed
Java 8 has Optional<T> which would make for one chained expression, though verbose.
However Java 8 also has Stream<T> and you could have a
"stream" of 0 or 1 item, and then query with lambdas.
x.getLocation()
.map((loc) -> loc.getBuilding())
.map((building) -> building.getSolidFuelInd() != null)
.findFirst()
.ifPresent ...
Or
x.getLocation()
.map(Location::getBuilding)
.map(Building::getSolidFuelInd())
.filter(fuelInd -> fuelId != null)
.findFirst()
.ifPresent ...
It probably will be a matter of slow coming to terms with an application of those new terms.
You could just catch the exception
try{
pol.setWood_heat_ind(x.getLocation().getBuilding().getSolidFuelInd() ? "Y" : "N");
}catch(NullPointerException e){
//e.printStackTrace(); or whatever you want
}
(Referring to your possible solution) checking for the returned values implies invoking the same methods more the once, that's why I would use this solution.
As Jay Harris pointed out, you can obviously check the values and save the return parameter, without having to invoke the same method again. You can do it in many different ways, here one
Object loc=null,build=null;
Boolean SFI = ((loc=x.getLocation())==null?null:
((build=loc.getBuilding())==null?null:
(build.getSolidFuelInd())));
if(SFI!=null)pol.setWood_heat_ind(SFI?"Y":"N");
But is it worth it? I made this more complicated than it could on purpose, but anyway, why doing that if you can try...catch in two simple lines?

Null check coding standard [duplicate]

This question already has answers here:
Which has better performance: test != null or null != test [duplicate]
(8 answers)
Closed 9 years ago.
I have a doubt regarding coding standard of a null check.
I want to know the difference between
if(a!=null)
and
if(null!=a)
which one is better,which one to use and why?
Both are same in Java, as only boolean expressions can be inside an if. This is just a coding style preference by programmer and most of them use null != a.
The null != a is an old practice in programming languages like Java,C++ (called as Yoda Conditions).
As it is valid to write if (a = null) and accidentally assign null to the a so writing null first is a guard to stop this accident from happening.
There is no difference. But the first is more common. The second is also called "Yoda Conditions" because of its unnatural "grammar".
Once I was working in a project where the coding guideline was to use if (null != a) because they thought it is easier for the developer to understand that the constant value has to come first always (as in CONSTANT_VALUE.equals(variable). That was pretty annoying to me.
They're both the same. It depends on your coding style.
From the compiler's point of view, they're exactly the same. But the first form is more readable, so I'd advise you to use that one.
No difference betwwen them if statement works based on result of expression
so u write either if(a!=null) or if(null!=a) will produce true or false then result is evaluated.
So it doesnt matter you write which you like
They both are same. Although the first variant is common the second variant is useful if you know the first variable is not null
Example "some value".equals(your_variable) , some value can be any value you know is not null. This will avoid NPE when your_variable is null.
String str = "somevalue";
if(str != null && str.equals("somevalue")) { }
if("somevalue".equals(str)) { }
Both the conditions will be same if str is null or not.

difference between null != something and something != null

Is there a difference between null != something and something != null in Java. And if there is a difference then which one should I use and why??
There's no difference between null != something and something != null. You must be thinking about the person.getName().equals("john") and the "john".equals(person.getName()) difference: the first one will throw a NullPointerException if getName() returns null, while the second won't. But this is not applicable for the example of your question.
its probably comming from the so-called joda-conditions where you write "bla" == myVariable instead of myVariable == "bla" because it could happen to accidentially write myVariable = "bla" which returns "bla" in some languages but also assign "bla" to myVariable
I just want to point out that the "Yoda condition" rationale for doing this (in languages like C & C++) does not apply in this (Java) case.
Java does not allow general expressions to be used as statements, so both
something == null;
and
null == something;
would be compilation errors.
The types of something == null and something = null are different; boolean and some reference type respectively. In this case, it means that both:
if (something = null) {
...
}
and
if (null = something) {
...
}
would be compilation errors.
In fact, I can't think of a realistic example where null == something would be compilation error and something == null would not. Hence, it doesn't achieve anything in terms of mistake-proofing.
There is no difference, but some people use it for ease of readability in their code.
Point of view of performance there will be no difference, both sides of the operator are executed any way. But for a more readable code second one seems more readable
obj.getSomething().getAnotherThing().doSomething() != null
null != obj.getSomething().getAnotherThing().doSomething()
But if you are going to just compare a variable or parameter this is more readable
something != null
Of course this depends on sense of reader.
In java if we compare any, always we have to place variables at left hand side and values are placed at right hand side...
They are both the same there is no difference.

Categories

Resources