2

Can any Java proficient / expert suggest me what is the optimistic way of checking null reference or objects before using it to avoids NullPointerException?

In my code I've more than 100 fields and most of them are required in order to pass value in request, but I need to perform null checks every time before passing it in request to avoid NullPointerException

I have shown below a little piece of code where I'm checking for null values every time for each field (lets say of more 70 times in my one file) which looks not good, code become very ugly and unreadable. Is there any way by which we can write method and perform null object checks through it?

Basically I'm looking better, Optimistic and faster way for doing this, Any quick help is much needed.

if(amount != null && amount != "" && !amount.isEmpty())
        AIMRequest.put("x_Amount", amount);

if(currency != null && currency != "" && !currency.isEmpty())
        AIMRequest.put("x_Currency_Code", currency);

if(expDate != null && expDate != "" && !expDate.isEmpty())
        AIMRequest.put("x_Exp_Date", expDate);

...........so on

2 Answers2

4
add("x_Amount", amount);
add("x_Currency_Code", currency);
add("x_Exp_Date", expDate);

void add(String name, String value)
{
    if(value!=null && !value.isEmpty())
        AIMRequest.put(name, value); 
}
ZhongYu
  • 18,232
  • 5
  • 28
  • 55
1

According your if's, conditions you are comparing Strings, so make a method:

public boolean isValid(String s) {
    return s != null && s != "" && !s.isEmpty();
}

If you want to compare objects with this methods change the signature public boolean isValid(Object o),

and your code will be clean as this:

if(isValid(amount))
        AIMRequest.put("x_Amount", amount);

if(isValid(currency)
        AIMRequest.put("x_Currency_Code", currency);

if(isValid(expDate)
        AIMRequest.put("x_Exp_Date", expDate);

But if you can collect all objects in an array:

public boolean isValid(Object[] os) {
    for (String s : os) {
        boolean isValid = s != null && s != "" && !s.isEmpty();
        if (!isValid) return false;
    }
    return true;
}
Jordi Castilla
  • 24,953
  • 6
  • 58
  • 97