Question

I'm using log4net in an application for logging.

I want to avoid a discussion about implementing a logging facade, but essentially, I'm creating some classes which will allow an ILog implementation to be injected via the constructor. Eg:

abstract class MigratorBase<T> : IMigrator<T>
{
        private ILog logger;

        public MigratorBase(ILog logger)
        {
            this.logger = logger;
        }
}

I also would like to provide a default constructor on the class, which if called, essentially disables logging (or logs to nothing). Instead of scattering fragments of code that check if the logger is null, such as this:

if (this.logger != null)
   Log.DebugFormat("Connecting to {0}", this.href);

I thought a better way to accomplish this functionality would be to assign an implementation of ILog that was purely empty methods. I could call it a NullLog, and would look similar to this:

class NullLog : ILog
{
    public void Debug(object message, Exception exception) { }
    public void Debug(object message) { }
    public void DebugFormat(IFormatProvider provider, string format, params object[] args) { }
    ...
    ...
}

and then in the default constructor I could assign an object of this type to the class's private member, as such:

abstract class MigratorBase<T> : IMigrator<T>
{
        private ILog logger;

        public MigratorBase(ILog logger)
        {
            this.logger = logger;
        }

        public MigratorBase()
        {
            this.logger = new NullLog();
        }
}

This approach seems more object oriented to me, so I think I like it, but googling seems to reveal people suggesting that it's a bad idea to implement an interface with empty methods.

Can anyone suggest why the above might be a bad idea? Or is it in fact an ok idea?

Was it helpful?

Solution

What you describe is called the Null Object pattern. Martin Fowler coined this term and explains it thoroughly in the book Patterns of Enterprise Application Architecture.

I think this is a great pattern to remove all the if-conditions in the code to check for not null. A downside could be that you have to explain a pattern in you development team and maybe add a comment about not adding functionality inside your NullLog class. Otherwise I couldn’t find a downside with this pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top