Chapter 9. Limiting Dependencies

The fewer dependencies the code you write has on other code, the easier it will be to change and the more resilient it will be when faced with changes elsewhere. If your code depends directly on code that you don't own, it is liable to be fragile and susceptible to breaking changes. That means that if you have a compile-time dependency on another package that you didn't write, you are in some respects at the mercy of whoever developed that package.

A compile-time dependency means a direct reference to a "foreign" library/package/assembly that makes it necessary for the compiler to have access to that foreign library. For example, to add some simple logging to a piece of .NET code, you might use the popular log4net library from the Apache Foundation. The following code shows a compile-time dependency on log4net.

public class Dependent
{
   private static readonly ILog log = LogManager.GetLogger(typeof(
Dependent));

   public int Add(int op1, int op2)
   {
       int result = op1 + op2;

       log.Debug(string.Format("Adding {0} + {1} = {2}", op1, op2, result));

       return result;
   }
}

This call to log4net's ILog.Debug method will log the message you compose to whatever log writers are configured currently. That might mean writing out the log message to the debug console, to a text file, or to a database. It is simple, easy to use, and provides a lot of functionality that you then don't have to write yourself.

However, you've now incurred a compile-time dependency on the log4net ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.