How to avoid null checking in Java?

后端 未结 30 3201
失恋的感觉
失恋的感觉 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:40

    I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.

    NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.

    Now to the answer:

    Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.

    Of course, experience is the better way to understand and apply this suggestion.

    Byte!

提交回复
热议问题