We all have ignored nulls at some point of time without considering the consequences. Most often newbie programmers are more prone to making this
mistake since they assume the value will be there or they don't bother to
check if null can be one of the possible return values of a method.This
often results in disaster at the most unexpected time.
Here are some typical scenarios when one could miss the null checking.
1)Null checking on collections returned by method calls.
If code uses the the above method as follows.
2)Wrong order of null checking.
3)null Strings
A quick way to fix the above is to rewrite it as follows:
4)Forgetting to assign a default value.
value can still be null.Assign a default to avoid further null checks and
exceptions.
mistake since they assume the value will be there or they don't bother to
check if null can be one of the possible return values of a method.This
often results in disaster at the most unexpected time.
Here are some typical scenarios when one could miss the null checking.
1)Null checking on collections returned by method calls.
List<String>getCustomers(Long acId){
...
...
if(noCustomers){
return null;
}
}
If code uses the the above method as follows.
List<String>customers=getCustomers(10);
if(!customers.isEmpty()){//throws NPE when getCustomers()returns null.
}
2)Wrong order of null checking.
if(!customers.isEmpty()&&customers!=null){
}
3)null Strings
String value=getFromSomeMethod();
if(value.equals("TEST")){
}
A quick way to fix the above is to rewrite it as follows:
if("TEST".equals(value)){
}
4)Forgetting to assign a default value.
String value=null;
if(condition1){
value=getSomething1();
}else if(condition2){
value=getSomething2();
}
value can still be null.Assign a default to avoid further null checks and
exceptions.
if(value==null){
value="";//default.
}
No comments:
Post a Comment