Architecture: Don't Marry The Framework

I've read a book by Robert C. Martin book titled Clean Architecture: A Craftsman's Guide to Software Structure and Design and was amazed by one statement in the book:

Don't marry the framework.

Robert C. Martin

Based on Uncle Bob's opinion, coupling a third-party library directly into our code is not a wise decision to make. What if the library got breaking changes on its update? What if the library is not updated to the latest version of the .NET Framework that you'll be going to use?

Class Dependency vs Interface Dependency

Let's see one of the examples of the code that is coupled directly to the third-party library. Let's say I have a business requirement to do logging and I'm using NLogfor this sample:

public static class Program
{
    private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

    public void Main()
    {
        try
        {
           Logger.Info("Hello world");
           System.Console.ReadKey();
        }
        catch (Exception ex)
        {
           Logger.Error(ex, "Goodbye cruel world");
        }
    }
}  

Logger property in that code is coupled directly to the NLog class and will be troublesome for us if, in the future, we won't use the NLog anymore. So the better approach for this kind of thing is to wrap the class in our interface. So this is what I'm going to do:

    public interface ILog
    {
        void Info(string text);
        void Error(string text);
    }

    public class NlogLogger : ILog
    {
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        public void Info(string text)
        {
            Logger.Info(text);
        }

        public void Error(string text)
        {
            Logger.Error(text);
        }
    }

Then for the Program.cs you can change like this:

public static class Program
{
    private static readonly ILog Logger = new NlogLogger();

    public void Main()
    {
        try
        {
           Logger.Info("Hello world");
           System.Console.ReadKey();
        }
        catch (Exception ex)
        {
           Logger.Error(ex, "Goodbye cruel world");
        }
    }
}  

So what is the point of the statement "Don't marry the framework"? What we did was avoid the direct dependency on the third-party library. With this approach, if we want to change the library that we're using. We can achieve those things more easily because we need to change only the implementation of the ILog to whatever code you want.

Leave a comment

Your comment is sent privately to the author and isn't published on the site.