The Null Object Pattern is a pattern that uses objects with null behavior instead of performing null checks throughout the codebase. ILogger[ ](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.logging.ilogger?view=dotnet-plat-ext-3.1)and ILoggerFactory are dependencies that often require a lot of null checking, so they are perfect candidates for the null object pattern. Suppose your classes take ILogger or ILoggerFactory as a dependency, and you are not using the null object pattern. In that case, you will probably find that your code is either subject to NullReferenceExceptions, or forcing implementors to supply loggers as arguments. Use the null object pattern to avoid both these problems. This article teaches you how in C#.

“Null object” might be confusing for some people because it seems to imply that the object reference might be null. However, the opposite is true. The object will never be a null reference. Null refers to the behavior of the object – not the reference itself. I think that a better name for the pattern would be “Dummy Object Pattern” since the objects you will use are shells with no behavior.

Why Use the Null Object Pattern?

If you inject dependencies into your classes, you need to validate against null or perform null checking throughout your code. The null conditional operator ?. helps, but it is still very easy to miss one. Every single missed question mark is a bug in the code. The null object pattern gives you a third option of using a dummy object instead. This reduces the number of code paths and therefore decreases the chance of NullReferenceExceptions while still allowing the implementor to instantiate the class without creating an instance of the dependency.

In the case of ILogger, it is quite onerous to create an implementation. Simply put, you shouldn’t do it. If you want to implement logging, you should use an existing logging library. It becomes even more onerous if the dependency is ILoggerFactory. The implementor needs to pull in external dependencies or create a cascading set of classes that they may have no idea how to implement. It gets much worse when you try to mock ILogger or ILoggerFactory dependencies. Although it is still important to verify that logging gets called. You can read about that here.

#.net #c# #logging #software #ilogger #iloggerfactory #logging #nullobjectpattern #nullreferenceexception

ILogger and Null Object Pattern
3.00 GEEK