How to avoid null checking in Java?

后端 未结 30 3330
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
30条回答
  •  梦谈多话
    2020-11-21 05:33

    This is the most common error occurred for most of the developers.

    We have number of ways to handle this.

    Approach 1:

    org.apache.commons.lang.Validate //using apache framework
    

    notNull(Object object, String message)

    Approach 2:

    if(someObject!=null){ // simply checking against null
    }
    

    Approach 3:

    @isNull @Nullable  // using annotation based validation
    

    Approach 4:

    // by writing static method and calling it across whereever we needed to check the validation
    
    static  T isNull(someObject e){  
       if(e == null){
          throw new NullPointerException();
       }
       return e;
    }
    

提交回复
热议问题