java - eclipse autogenerates !=null recursive calls -


given java code such as:

something v = a.getb().getc().getd().gete(); 

is there way in eclipse (templates or external plugins) generate safe chain call as:

if(a!=null &&     a.getb()!=null &&    a.getb().getc()!=null &&    a.getb().getc().getd()!=null &&            a.getb().getc().getd().gete()!=null){           v = a.getb().getc().getd().gete();     }         

have given thought try{} catch(nullpointerexception e){} block? might feel less elegant, stop code if of method calls fails because previous 1 returned null, , give chance give default value if null.

another option this:

something v = /*default value*/ // overwritten if subsequent methods succeed. object temp = a.getb(); // use whatever object type getb() returns. if(temp != null){     temp = temp.getc();      /* if getc() returns different type of object,       * either use different variable or make temp variable broader       * (such generic object type) */     if(temp != null){         temp = temp.getd();         if(temp != null){             temp = temp.gete();             if(temp != null)                 v = temp;                  /* if previous calls returned substantial,                   * v useful */             }//if(gete() != null)         }//if(getd() != null)     }//if(getc() != null) }//if(getb() != null) 

if want, use less cpu efficient, easier read, version not nesting if statements. if of if statements executed after eachother, single null prevent of next statements executing, although value still checked every time.

as far generating these statements, i'm not sure. depend on how far in advance can predict new methods available object returned previous method calls. if you're aiming auto-generation of code, might better off first suggestion: try-catch


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -