Architecture: Don’t Marry The Framework

I’ve read a book from Robert C. Martin book title Clean Architecture: A Craftsman’s Guide to Software Structure and Design and got amazed by one statement in the book:

Don’t marry the framework.

Robert C. Martin

Based on Uncle Bob’s opinion, coupled 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 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 NLog for 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 how 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 is 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 easier because we need to change only the implementation of the ILog to whatever code you want.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.