2

In my code, I need to do something like this: System.out.println(obj1.getObj2().getObj3().getObj4()); but all objects are possible to be null, so I have to write like this:

   if (obj1 == null) {
            System.out.println("");
    }
    else if (obj1.getObj2() == null) {
        System.out.println("");
    }
    else if (obj1.getObj2().getObj3() == null) {
        System.out.println("");
    }
    else if (obj1.getObj2().getObj3().getObj4() == null) {
        System.out.println("");
    }
    else {
        System.out.println(obj1.getObj2().getObj3().getObj4());
    }

Is there anyway that I am simplify the above code? Remarks: I am using J2SE 6.0

1
  • Which java version is in use? Commented Feb 17, 2016 at 6:34

5 Answers 5

4

Certainly not the best solution around (but this code is way cleaner than the if -else approaches :P.. * probably slower but cleaner* :

public static String getValue(SomeClass obj1) {
    String s = "";
    try {
       s =  obj1.getObj2().getObj3().getObj4().toString();
    }
    catch (NullPointerException ex) {
        // set s to something else if you want to.
    }
    return s;
}

And you can use : System.out.println(getValue(obj1));

Sign up to request clarification or add additional context in comments.

2 Comments

obj1.getObj2().getObj3().getObj4() should not always return string. I think rewrite obj1.getObj2().getObj3().getObj4().toString();
@mmuzahid - Yes. That code is untested. I had missed the semi-colon too :P
4

if clauses will be checked from left to right, so you can write:

if (obj1 == null || 
            obj1.getObj2() == null || 
            obj1.getObj2().getObj3() == null || 
            obj1.getObj2().getObj3().getObj4() == null) {
        System.out.println("");
} else {
    System.out.println(obj1.getObj2().getObj3().getObj4());
}

In this code, if obj1 == null, the other conditions won't be checked anymore.

Comments

2
if(obj1 == null || obj1.getObj2() == null || obj1.getObj2().getObj3() == null ||  obj1.getObj2().getObj3().getObj4() == null){
System.out.println("");
}
else{
System.out.println(obj1.getObj2().getObj3().getObj4());
}

Comments

2

An alternative approach

Obj2Type obj2 = obj1==null ? null : obj1.getObj2();
Obj3Type obj3 = obj2==null ? null : obj2.getObj3();
Obj4Type obj4 = obj3==null ? null : obj4.getObj4();
System.out.println(obj4==null ? "" : obj4.toString()); // toString() in case obj4 is not String

Comments

0

If you are in control of all that methods source code, then you can use null object that will return itself on all subsequent calls. Other option is to use something like maybe monad and then chain it by some kind of bind operation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.