java - Avoiding != null statements -


the idiom use when programming in java test if object != null before use it. avoid nullpointerexception. find code ugly, , becomes unreadable.

is there alternative this?

i want address necessity test every object if want access field or method of object.

for example:

if (someobject != null) {     someobject.docalc(); } 

in case avoid nullpointerexception, , don't know if object null or not. these tests appear throughout code consequence.

this me sounds reasonably common problem junior intermediate developers tend face @ point: either don't know or don't trust contracts participating in , defensively overcheck nulls. additionally, when writing own code, tend rely on returning nulls indicate requiring caller check nulls.

to put way, there 2 instances null checking comes up:

  1. where null valid response in terms of contract; and

  2. where isn't valid response.

(2) easy. either use assert statements (assertions) or allow failure (for example, nullpointerexception). assertions highly-underused java feature added in 1.4. syntax is:

assert <condition> 

or

assert <condition> : <object> 

where <condition> boolean expression , <object> object tostring() method's output included in error.

an assert statement throws error (assertionerror) if condition not true. default, java ignores assertions. can enable assertions passing option -ea jvm. can enable , disable assertions individual classes , packages. means can validate code assertions while developing , testing, , disable them in production environment, although testing has shown next no performance impact assertions.

not using assertions in case ok because code fail, happen if use assertions. difference assertions might happen sooner, in more-meaningful way , possibly information, may figure out why happened if weren't expecting it.

(1) little harder. if have no control on code you're calling you're stuck. if null valid response, have check it.

if it's code control, (and case), it's different story. avoid using nulls response. methods return collections, it's easy: return empty collections (or arrays) instead of nulls pretty time.

with non-collections might harder. consider example: if have these interfaces:

public interface action {   void dosomething(); }  public interface parser {   action findaction(string userinput); } 

where parser takes raw user input , finds do, perhaps if you're implementing command line interface something. might make contract returns null if there's no appropriate action. leads null checking you're talking about.

an alternative solution never return null , instead use null object pattern:

public class myparser implements parser {   private static action do_nothing = new action() {     public void dosomething() { /* nothing */ }   };    public action findaction(string userinput) {     // ...     if ( /* can't find actions */ ) {       return do_nothing;     }   } } 

compare:

parser parser = parserfactory.getparser(); if (parser == null) {   // what?   // example of null isn't (or shouldn't be) valid response } action action = parser.findaction(someinput); if (action == null) {   // nothing } else {   action.dosomething(); } 

to

parserfactory.getparser().findaction(someinput).dosomething(); 

which better design because leads more concise code.

that said, perhaps entirely appropriate findaction() method throw exception meaningful error message -- in case relying on user input. better findaction method throw exception calling method blow simple nullpointerexception no explanation.

try {     parserfactory.getparser().findaction(someinput).dosomething(); } catch(actionnotfoundexception anfe) {     userconsole.err(anfe.getmessage()); } 

or if think try/catch mechanism ugly, rather nothing default action should provide feedback user.

public action findaction(final string userinput) {     /* code return requested action if found */     return new action() {         public void dosomething() {             userconsole.err("action not found: " + userinput);         }     } } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -