-1

I have a list saSpComplianceInsuranceList. And it has SaSpComplianceInsurance objects. I have to iterate through each object, and check if the members of object are null or not null. If null nothing should be done. If not null and negative, it should throw an error saying "cannot be negative". These null and not null conditions have to be checked on each member of the object.

For example:

   int index = 0;
   for (SaSpComplianceInsurance saSpComplianceInsurance : saSpComplianceInsuranceList)
   {
       if(saSpComplianceInsurance.getCoverageAmount() != null)
       {
           if(saSpComplianceInsurance.getCoverageAmount() < 0.0)
           {
               fieldErrors.add(new FieldError("pageEntity.saSpComplianceInsuranceList["+index+"].coverageAmount", "genericSpMaintenance.amount.negative", resourceBundle.getString("genericSpMaintenance.InsuranceType." + saSpComplianceInsurance.getInsuranceTypeCode()), resourceBundle.getString("genericSpMaintenance.saSpComplianceInsuranceList.coverageAmount")));
           }
       }

Now I am stuck at this point. When my control reaches first if statement with a null value it is throwing a NullPointerException. If I write this code in try/catch block, what should be written in catch block, so that validation should pass and allow null values?

navya chamidisetty
  • 341
  • 1
  • 2
  • 11

1 Answers1

1

You can update the condition from:

if(saSpComplianceInsurance.getCoverageAmount() != null)

to

if(saSpComplianceInsurance !=null) { 
    if(saSpComplianceInsurance.getCoverageAmount() != null)

Also with the current conditions, you can shorten your code then to

if(saSpComplianceInsurance !=null
     && saSpComplianceInsurance.getCoverageAmount() != null
     && saSpComplianceInsurance.getCoverageAmount() < 0.0) {

     fieldErrors.add(new FieldError("pageEntity.saSpComplianceInsuranceList["+index+"].coverageAmount", "genericSpMaintenance.amount.negative", resourceBundle.getString("genericSpMaintenance.InsuranceType." + saSpComplianceInsurance.getInsuranceTypeCode()), resourceBundle.getString("genericSpMaintenance.saSpComplianceInsuranceList.coverageAmount")));
}

which can be further improved as

// util to check all conditions
boolean nullConditionsHandled(SaSpComplianceInsurance saSpComplianceInsurance) {
    returns saSpComplianceInsurance !=null
     && saSpComplianceInsurance.getCoverageAmount() != null
     && saSpComplianceInsurance.getCoverageAmount() < 0.0;
}
....

if(nullConditionsHandled(saSpComplianceInsurance)) {
     fieldErrors.add(new FieldError("pageEntity.saSpComplianceInsuranceList["+index+"].coverageAmount", "genericSpMaintenance.amount.negative", resourceBundle.getString("genericSpMaintenance.InsuranceType." + saSpComplianceInsurance.getInsuranceTypeCode()), resourceBundle.getString("genericSpMaintenance.saSpComplianceInsuranceList.coverageAmount")));
}
Naman
  • 27,789
  • 26
  • 218
  • 353