avoiding null reference exceptions

后端 未结 15 993
天命终不由人
天命终不由人 2020-11-28 08:50

Apparently the vast majority of errors in code are null reference exceptions. Are there any general techniques to avoid encountering null reference errors?

Unless I

相关标签:
15条回答
  • 2020-11-28 09:37

    Tools that can help

    There are also several libraries that can help. Microsoft Code Contracts was mentioned above.

    Some other tools include Resharper which can provide you with warnings while you are writing code, especially if you use their attribute: NotNullAttribute

    There's also PostSharp which will allow you to just use attributes like this:

    public void DoSometing([NotNull] obj)
    

    By doing that and making PostSharp part of your build process obj will be checked for null at runtime. See: PostSharp null check

    The Fody code-weaving project has a plug-in for implementing null guards.

    0 讨论(0)
  • 2020-11-28 09:38

    You can easily check for a null reference before it causes an exception, but usually that is not the real problem, so you would just end up throwing an exception anyway as the code can't really continue without any data.

    Often the main problem isn't the fact that you have a null reference, but that you got a null reference in the first place. If a reference is not supposed to be null, you shouldn't get past the point where the reference is initialised without having a proper reference.

    0 讨论(0)
  • 2020-11-28 09:38

    One of the simplest ways to avoid NullReferenceExceptions is to aggressively check for null references in your class constructors/methods/property setters and draw attention to the problem.

    E.g.

    public MyClass
    {
       private ISomeDependency m_dependencyThatWillBeUsedMuchLater 
    
       // passing a null ref here will cause 
       // an exception with a meaningful stack trace    
       public MyClass(ISomeDependency dependency)
       {
          if(dependency == null) throw new ArgumentNullException("dependency");
    
          m_dependencyThatWillBeUsedMuchLater = dependency;
       }
    
       // Used later by some other code, resulting in a NullRef
       public ISomeDependency Dep { get; private set; }
    }
    

    In the above code, if you pass a null ref, you will find out immediately that the calling code is using the type incorrectly. If there was no null reference check, the error can be obscured in many different ways.

    You'll notice that the .NET framework libraries nearly always fail early and often if you provide null references where it's invalid to do so. Since the exception thrown explicitly says "you messed up!" and tells you why, it makes detecting and correcting defective code a trivial task.

    I've heard complaints from some developers who say this practice is overly verbose and redundant as a NullReferenceException is all you need, but in practice I find it makes a big difference. This is especially the case if the call stack is deep and/or the parameter is stored and its use is deferred until later (perhaps on a different thread or obscured in some other way).

    What would you rather have, an ArgumentNullException at the entry method, or an obscure error in the guts of it? The further you move away from the source of an error, the harder it is to trace it.

    0 讨论(0)
提交回复
热议问题