How much null checking is enough?

后端 未结 18 1321
清酒与你
清酒与你 2021-01-30 01:10

What are some guidelines for when it is not necessary to check for a null?

A lot of the inherited code I\'ve been working on as of late has null-checks

18条回答
  •  一个人的身影
    2021-01-30 01:36

    One thing to remember that your code that you write today while it may be a small team and you can have good documentation, will turn into legacy code that someone else will have to maintain. I use the following rules:

    1. If I'm writing a public API that will be exposed to others, then I will do null checks on all reference parameters.

    2. If I'm writing an internal component to my application, I write null checks when I need to do something special when a null exists, or when I want to make it very clear. Otherwise I don't mind getting the null reference exception since that is also fairly clear what is going on.

    3. When working with return data from other peoples frameworks, I only check for null when it is possible and valid to have a null returned. If their contract says it doesn't return nulls, I won't do the check.

提交回复
热议问题