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
11
  • 4
    Make a method for this. DRY Commented May 12, 2015 at 21:24
  • 1
    @HovercraftFullOfEels Do you mean DRY? :) nvm. Commented May 12, 2015 at 21:25
  • @keyser: I had to look that one up. Commented May 12, 2015 at 21:26
  • 2
    Related: stackoverflow.com/questions/271526/… Commented May 12, 2015 at 21:28
  • 1
    amount != "" && !amount.isEmpty() is the same as !amount.isEmpty() Commented May 12, 2015 at 21:33

2 Answers 2

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); 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi bayou.io - Does this will increase performance etc?
@user4567570 - don't worry about it; JVM very likely will optimize it.
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;
}

1 Comment

Hi Jordi - Does that will increase performance?