Reputation: 244
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
Upvotes: 2
Views: 825
Reputation: 23556
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.
Upvotes: 0
Reputation: 86764
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
Upvotes: 2
Reputation: 36304
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));
Upvotes: 4
Reputation: 267
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());
}
Upvotes: 2
Reputation: 2916
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.
Upvotes: 4