java - should I pay much attention on NullPointerException? -
when use junit test check coding process,i find there problems bother me. example:
list<user> list = userdao.findby("id",id); list.get(0).getname();
there problem.i didn't use assert check list not null before using may cause nullpointexception.but @ business logic.
when create new user this.
if(user!=null){ userdao.save(user) }
it should not null.because check user not null when add one, know user successful in database.
if add lot of when user:
if(list!=null||list.size()>0){...};
in similar place makes code chaos.
should add or not?how make choice? thx anyway.
i think looking method preconditions or, more generally, contracts.
let's assume code split many small methods, should be. define preconditions , postconditions every method. these need met, otherwise failure expected. if consistently, question of put these checks pretty answer in quite intuitive way.
as example, let's consider 2 ways write method user
:
private void dosomethingwithuser(user u) { if (u == null) { /* take appropriate steps */ } /* perform action on user object */ }
above, method takes care of null-check. hence, there no need calling code it.
/* * , user. * precondition: user `u` may not null! */ private void dosomethingwithuser(user u) { /* perform action on user object */ }
here, method not check u
null
, reading comment, can see how method designed. responsibility of calling code hand in non-null object, else behavior undefined.
of course, face decision of when go of these. , obviously, can set preconditions methods and have them still perform appropriate checks. return value indicates error or throw exception, pretty common.
edit:
but if there lots of objects need check before use them?should check them all?
consider this:
public class simpleclass { public static void main (string[] args) { user sware = new user("sware"); user domdom = new user("domdom"); dosomethingwithuser(sware); dosomethingwithuser(domdom); } }
here, declaring and initializing 2 objects in main
method. know not null. use them right away. no matter if method checks null
or not, not perform such check outside - there no way objects null
.
now, imagine have more complex code:
public class verycomplexclass extends complexclass implements complexinterface { /* ... */ @override private boolean dosomethingwithuser(user u) { if (u == null) { return false; } /* ... */ } }
let's need implement dosomethingwithuser()
method satisfy interface. or method comes parent class , override it. don't know u
coming from. potentially call method? user outside of class? or method being used class itself? called member being passed in? pretty hard tell @ point. hence, recommend put null
check place.
Comments
Post a Comment