java - calling function should return default value, if object (or any function result) is null -


is possible wrap following code in reusable function?

edit: this example, want working solution recursion depths

what want following code generated:

if (myobject o == null ||      o.getsubobject() == null ||     o..getsubobject().getsubsubobject() == null /*||      ... */)     return defaultvalue; return o.getsubobject().getsubobject()/*...*/.getdesiredvalue(); 

by calling like

object defaultvalue = null; object result = nullsafecall(o.getsubobject().getsubobject()/*...*/.getdesiredvalue(), defaultvalue); 

the seond code block idea, don't care how looks like, want i, if desired, can avoid null checks before calling deeper function...

injection propably, there no other/easier solution? never looked @ injection before yet...

edit2: example in language: http://groovy.codehaus.org/operators#operators-safenavigationoperator

not really, code write way horrible and/or use slow reflection. unless use actual java preprocessor can understand , change code you've written.

a better (but associated quite bit of refactoring) approach make sure values in question cannot possibly null. example, modify individual accessors (getsubobject(), getdesiredvalue()) never return null in first place: make them return default values. accessors on default values return default values in turn.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -