How to avoid null checking in Java?

后端 未结 30 3333
失恋的感觉
失恋的感觉 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条回答
  •  猫巷女王i
    2020-11-21 05:41

    May I answer it more generally!

    We usually face this issue when the methods get the parameters in the way we not expected (bad method call is programmer's fault). For example: you expect to get an object, instead you get a null. You expect to get an String with at least one character, instead you get an empty String ...

    So there is no difference between:

    if(object == null){
       //you called my method badly!
    

    }

    or

    if(str.length() == 0){
       //you called my method badly again!
    }
    

    They both want to make sure that we received valid parameters, before we do any other functions.

    As mentioned in some other answers, to avoid above problems you can follow the Design by contract pattern. Please see http://en.wikipedia.org/wiki/Design_by_contract.

    To implement this pattern in java, you can use core java annotations like javax.annotation.NotNull or use more sophisticated libraries like Hibernate Validator.

    Just a sample:

    getCustomerAccounts(@NotEmpty String customerId,@Size(min = 1) String accountType)
    

    Now you can safely develop the core function of your method without needing to check input parameters, they guard your methods from unexpected parameters.

    You can go a step further and make sure that only valid pojos could be created in your application. (sample from hibernate validator site)

    public class Car {
    
       @NotNull
       private String manufacturer;
    
       @NotNull
       @Size(min = 2, max = 14)
       private String licensePlate;
    
       @Min(2)
       private int seatCount;
    
       // ...
    }
    

提交回复
热议问题