Null Check in Code

classic Classic list List threaded Threaded
2 messages Options
J1234 J1234
Reply | Threaded
Open this post in threaded view
|

Null Check in Code

Everytime in Code review comments i get comments for null check. Just wanted to see if it makes sense to do a null check everywhere we access an object. In  which situations we should avoid null check. Moreover lets say i have a situation wherein i have to access obj within obj1 within obj2 which is again within obj 3. For ex

obj3.obj2.obj1.obj

Should i make null check for all objects in sequence

For example

If(obj3 != null && obj3.obj2!= null && obj3.obj2.obj1 != null){
      System.out.println(obj3.obj2.obj1.obj);
}    
John John
Reply | Threaded
Open this post in threaded view
|

Re: Null Check in Code

We should have null check where you expect the object to be null. For ex- By application logic if you are sure that obj3 and obj3.obj2 can't be null , you need not do a null check on them. we should have a null check for all objects which we feel that having null could be a expected scenerio. For rest others , it make sense to throw a NPE as stack trace could help in investigating the cause of Exception.