Java - How to deal with null value passed by argument? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I wrote this simple function:
private String getOperatorForCardinality(String op)
{
String operator ="";
if(op!=null)
{
if(op.equals(">="))
{
operator = ">=";
}
else if (op.equals("<="))
{
operator = "<=";
}
}
else
{
operator = "empty";
}
return operator;
}
which returns a string.
In the main program I call this function, when the argument is null the compiler displays the error of NullPointerException.
The reason is pretty clear, but I do not know how to deal with the null value when is passed by argument.

It is impossible for the code you posted to throw a NPE. The error is somewhere else, or you are not running the code you think you are (ie haven't recompiled etc).
That said, your method can be simplified to:
private static List<String> OPS = Arrays.asList("<=", ">="); // can add more valid ops
private static String getOperatorForCardinality(String op) {
if (op == null)
return "empty";
return OPS.contains(op) ? op : "";
}
Or if you don't mind nested ternaries:
private static String getOperatorForCardinality(String op) {
return OPS.contains(op) ? op : op == null ? "empty" : "";
}
Less code is usually clearer code, and leaves less places for bugs to lurk.

It is called defensive programming and you should do something like:
private String getOperatorForCardinality(String op) {
if(null == op) {
//return null;
//throw new NullPointerException("...");
}
....
}
You should think about how your method should react, need to return null if parameter is null or throw an exception? Generally you cant be sure a parameter will never be null so you have always to check and take action.

This can't throw a null pointer exception:
private String getOperatorForCardinality(String op)
{
String operator = "";
if(">=".equals(op))
{
operator = ">=";
}
else if ("<=".equals(op))
{
operator = "<=";
} else {
operator = "empty";
}
return operator;
}

try opposite
if (op==null)
operator = "empty";

Related

How to check null on Object where List<Object> Object contains Object? [duplicate]

This question already has answers here:
Two conditions in one if statement does the second matter if the first is false?
(7 answers)
Closed 2 years ago.
For Example:
public class HelpMetric {
private String metricId;
private String supportType;
private RequestSupportVo requestSupport;
}
public class RequestSupportVo {
private String requestSupportId;
}
public List<HelpMetric> getHelpMetric(String metricId) {
List<PolHelpMetric> list =helpMetricMapper.hlpMetricListToPolHelpMetricVoList(all);
list.forEach(x -> {
if (x.getRequestSupport() != null) {
if (x.getRequestSupport().getRequestSupportId() != null) {
}
}
}
How i can optimise this above codetwo if condition null check using Java 8
if (x.getRequestSupport() != null) {
if (x.getRequestSupport().getRequestSupportId() != null) {
Java's logical operators, like those in many other languages, exhibit short-circuit evaluation behavior.
So a conditional block like the following:
if (a.getB() != null) {
if (a.getB().getC() != null) {
// ...
}
}
Can safely be rewritten as:
if (a.getB() != null && a.getB().getC() != null) {
// ...
}
Due to the short-circuiting behavior, in case the first condition fails, the second condition will not be evaluated, and does not risk throwing a NullPointerException.

Check if any object in get chain is null without having to check each depth [duplicate]

This question already has answers here:
Null check chain vs catching NullPointerException
(19 answers)
Check chains of "get" calls for null
(11 answers)
Closed 3 years ago.
I'm working with a legacy application where I often have to access properties deeply nested like that:
a.getB().getC().getD().getE().getF()
The problem is that it's possible that in any depth, the value could be null. Of course I could check each depth like that:
public Optional<F> retrieveValue(A a) {
if(a != null && a.getB() != null && a.getB().getC() != null &&
a.getB().getC().getD() != null &&
a.getB().getC().getD().getE() != null &&
a.getB().getC().getD().getE().getF() != null) {
return Optional.of(a.getB().getC().getD().getE().getF());
} else {
return Optional.empty();
}
}
F existingOrCreated = retrieveValue(a).orElse(new F());
But I have to do this in many places for many different objects so the code gets bloated with these checks. Mostly the objects are non null but there are some rare cases where objects are null. Is there a way to do it in a more concise way? I'm using Java 8 but I can't update the legacy code provided.
Before going into my answer I'd like to point out that these chains should be avoided in the first place. (Check the Law of Demeter).
Now to the problem. Because Java, unlike other languages like Kotlin does not provide simpler checking for nulls, until Java 8 you had only the choice to check each level of your object.
But since Java 8 offers function passing as parameters, I started using this feature to build my own "Safe Calls" in Java:
public static <T> Optional<T> retrieveValue(Supplier<T> getter) {
try {
return Optional.ofNullable(getter.get());
} catch (NullPointerException e) {
return Optional.empty();
}
}
Let's first see how this method is called in your given case:
F f = retrieveValue(() -> a.getB().getC().getD().getE().getF()).orElse(new F());
As you can see, we just pass a Supplier to retrieveValue and call it in a try-catch block where we catch the possible NullPointerException and return an Optional.empty() in that case.
A small disadvantage of this try-catch approach is, that it's slower than simple null check in the code if a NullPointerException occurs during checking.
Another advantage of this approach is, that this method is reusable for any other null checking in any depth and does not depend on a specific object structure.
Node node = retrieveValue(() -> root.getNode().getNode()).orElse(new Node());
Is there any chance that you could change the design such that A could simply have a getF method and the chaining is hidden in the other classes?
Something like:
public class E {
...
public F getF() {
return f; // F can be null
}
...
}
public class D {
...
public F getF() {
e == null ? null : e.getF();
}
...
}
public class C {
...
public F getF() {
d == null ? null : e.getF();
}
...
}
public class B {
...
public F getF() {
c == null ? null : e.getF();
}
...
}
public class A {
...
public F getF() {
b == null ? null : e.getF();
}
...
}
This way the null just gets propagated through the classes. You only need to check if a is null, or if a.getF() is null at the end, which will look way cleaner.

Java tryParseInt best practice [duplicate]

This question already has answers here:
Best implementation for an isNumber(string) method
(19 answers)
Closed 7 years ago.
I have a lot of code that gathers user input and parses it,
I want to parse integer values without throwing exceptions.
My current tryParseInt() function is code is simple:
public static Integer tryParseInt( String text )
{
if(text == null)
return null;
try
{
return new Integer( text.trim() );
}
catch ( NumberFormatException e )
{
return null;
}
}
But i am getting lots of NumberFormatExceptions and i am worried becouse that may impact my app performance.
Can anyone suggest me on best practice for parsing user inputs.
Thank you
You can go with regex as it is more fail proof
public static Integer tryParseInt(String text) {
if (text != null && !text.isEmpty()) {
if (text.trim().matches("[0-9]+")) {
return Integer.valueOf(text.trim());
}
}
return null;
}
This is a very helpful experiment and indeed my experience is removing exceptions is better for performance
If you are getting a lot of NumberFormatExceptions, you might consider checking the parsing input before the actual parsing.
BTW the return new Integer( text.trim() ); is not very efficient as you will be allocating a lot of unnecessary objects (in the range from -128 to 127).
public static Integer tryParseInt(String text) {
if(text == null)
return null;
try {
return Integer.valueOf(text.trim());
}
catch (NumberFormatException e) {
return null;
}
}

Avoid Literals In If Condition

This part of code is rejected by pmd in sonar:
public String getFoo() {
String foo = System.getProperty("foo");
if (foo == null) {
foo = System.getenv("foo");
} else if (foo == null) {
foo = "defaultFoo";
}
return foo;
}
It says "Avoid Literals In If Condition". Can someone tell me what's wrong with this or what this rule try to effect?
Why don't you use:
public String getFoo() {
String foo = System.getProperty("foo", "defaultFoo");
return foo;
}
It will return "defaultFoo" if no property is found.
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperty(java.lang.String, java.lang.String)
What does Sonar try to say is that you should avoid hardcoded literals (like null) in the if condition.
Suppose the following example:
Let's say we have this if statement, for which Sonar warns with Avoid Literals In If Condition:
if (i == 5) {
//do something
}
By declaring the hardcoded literal as (final) variable with descriptive names maintainability is enhanced:
final int FIVE = 5;
if (i == FIVE) {
//do something
}
and Sonar doesn't warn anymore.

calling function should return default value, if object (or any function result) is null

Is it possible to wrap following code in a reusable function?
EDIT: this is just an example, I want a working solution for ALL recursion depths
what I want is that following code is generated:
if (MyObject o == null ||
o.getSubObject() == null ||
o..getSubObject().getSubSubObject() == null /*||
... */)
return defaultValue;
return o.getSubObject().getSubObject()/*...*/.getDesiredValue();
by calling something like
Object defaultValue = null;
Object result = NullSafeCall(o.getSubObject().getSubObject()/*...*/.getDesiredValue(), defaultValue);
The seond code block is just an idea, I don't care how it looks like, all I want is that I, if desired, can avoid all the null checks before calling a deeper function...
Injection could do this propably, but is there no other/easier solution? Never looked at injection before yet...
EDIT2: example in another language: http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
Not really, any code you would write this way would look horrible and/or use very slow reflection. Unless you use an actual Java preprocessor that can understand and change the code you've written.
A better (but associated with quite a bit of refactoring) approach would be to make sure that the values in question cannot possibly be null. For example, you could modify the individual accessors (getSubObject(), getDesiredValue()) to never return null in the first place: make them return default values. The accessors on the default values return default values in turn.
Java8 helps to get the closest you'll get to your syntax with decent performance I suspect;
// Evaluate with default 5 if anything returns null.
int result = Optional.eval(5, o, x->x.getSubObject(), x->x.getDesiredValue());
This can be done with this utility class;
class Optional {
public static <T, Tdef, T1> Tdef eval(Tdef def, T input, Function<T,T1> fn1,
Function<T1, Tdef> fn2)
{
if(input == null) return def;
T1 res1 = fn1.apply(input);
if(res1 == null) return def;
return fn2.apply(res1);
}
}
Sadly, you'll need a separate eval() defined per number of method calls in the chain, so you may want to define a few, but compile time type safe and reusable with just about any calls/types.
You can do something like this
public static Object NullSafeCall(MyObject o,Object defaultValue){
if ( o == null || o.getSubObject() == null)
{
return defaultValue;
}
else
{
return o.getSubObject().getDesiredValue();
}
}
Now you can call this method as follows
Object result = NullSafeCall(o, defaultValue);
i would suggest just replace
Object result = NullSafeCall(o.getSubObject().getDesiredValue(), defaultValue);
by the
Object result = (o == null || o.subObject == null) ? defaultVlue : o.getSubObject().getDesiredValue();
Create method only if you can reuse it......
What you want is not possible. It is essential to understand that using this syntax: Object result = NullSafeCall(o.getSubObject().getSubObject() ...); the part of o.getSubObject().getSubObject() will be evaluated before any control passes to the function/method thus throwing the exception.
It is required to have some type of context before executing such code. The closest to this I could think of, can be done using anonymous inner classes like the example below:
// intended to be implemented by an anonymous inner class
interface NullSafeOperation<T> {
public T executeSafely();
};
// our executor that executes operations safely
public static class NullSafeExecutor<T> {
public NullSafeExecutor() {}
public T execute(T defaultValue, NullSafeOperation<T> nso) {
T result = defaultValue;
try {
result = nso.executeSafely();
} catch(NullPointerException e) {
// ignore
}
return result;
}
// utility method to create a new instance and execute in one step
public static <T> T executeOperation(T defaultValue, NullSafeOperation<T> nso) {
NullSafeExecutor<T> e = new NullSafeExecutor<T>();
T result = e.execute(defaultValue, nso);
return result;
}
}
public static void main(String[] args) {
final String aNullString = null;
String result = NullSafeExecutor.executeOperation("MyDefault", new NullSafeOperation<String>() {
#Override
public String executeSafely() {
// trying to call a method on a null string
// it will throw NullPointerException but it will be catched by the executor
return aNullString.trim();
}
});
System.out.println("Output = " + result); // prints: Output = MyDefault
}

Categories