How much null checking is enough?

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

    Part of this depends on how the code is used -- if it is a method available only within a project vs. a public API, for example. API error checking requires something stronger than an assertion.

    So while this is fine within a project where it's supported with unit tests and stuff like that:

    internal void DoThis(Something thing)
    {
        Debug.Assert(thing != null, "Arg [thing] cannot be null.");
        //...
    }
    

    in a method where you don't have control over who calls it, something like this may be better:

    public void DoThis(Something thing)
    {
        if (thing == null)
        {
            throw new ArgumentException("Arg [thing] cannot be null.");
        }
        //...
    }
    

提交回复
热议问题