Pages

Tuesday, June 12, 2012

Null Pointer Exceptions

I have a very complex  POJO (say object within objects within objects). All the attributes in it can potentially hold null.
 How can i operate on it without causing null pointer exceptions,  the only way is to do null checks on all the attributes at all the places i use them ?

Any other Ideas ?

3 comments:

  1. Code the getter to return a non-null object if the value of that attribute is null

    Just a thought, i am not sure if that's the best practice.

    //POJO class
    private String _someValue;

    public String getSomeValue() {
    if (_someValue == nul) {
    return new String();
    }
    return _someValue;
    }

    ReplyDelete
  2. we all know if there could be null object, we should do the check for null... so just sharing my take on why we should check for null than trying to do anything else...

    IMO, if we anticipate there will be null objects, its best to check in the code and avoid processing rather than throw the exception... frequent exceptions will dump huge string and fill-up the logs very quickly...

    and secondly, we shouldn't have monster object structure because its defeating the concept of balance between conciseness and coherence... if in this case due to POJO, we happen to have huge structure, I will go with you by processing nested objects into separate functional units and check for null rather than handling it through try/catch.

    ReplyDelete
  3. Thanks for your comments.

    I went with checking for null everywhere i use them , i am saved here a bit as some of the fields are mandatory and must be provided a value.

    In the other optional cases i always do a null check before working with it, but it does make the code look verbose.

    @Ramchel: about the monster object structure , i too hate it , but think of the objects i am dealing with as the Object binding for a V3 standard HL7 XML message containing all the patient details.something like this...

    Patinet
    -Person
    -Telecom Address
    -Names
    -LEGAL
    -FIRST
    -LAST
    -PRE MARRIAGE
    -VacationAdress
    -DichargeDetails
    -AdmittingDiaog
    - ICDCODE
    Code
    authority
    -Name
    -Location
    etc etc

    Technically i have no choice.

    ReplyDelete