How much null checking is enough?

后端 未结 18 982
清酒与你
清酒与你 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:14

    Whether to check for null or not greatly depends on the circumstances.

    For example in our shop we check parameters to methods we create for null inside the method. The simple reason is that as the original programmer I have a good idea of exactly what the method should do. I understand the context even if the documentation and requirements are incomplete or less than satisfactory. A later programmer tasked with maintenance may not understand the context and may assume, wrongly, that passing null is harmless. If I know null would be harmful and I can anticipate that someone may pass null, I should take the simple step of making sure that the method reacts in a graceful way.

    public MyObject MyMethod(object foo)
    {
      if (foo == null)
      {
        throw new ArgumentNullException("foo");
      }
    
      // do whatever if foo was non-null
    }
    

提交回复
热议问题