DevIQ

Explicit Dependencies Principle

Explicit Dependencies Principle

The Explicit Dependencies Principle states:

Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.

If your classes require other classes to perform their operations, these other classes are dependencies.  These dependencies are implicit if they exist only in the code within your class, and not in its public interface.  Explicit dependencies appear most often in an object's constructor, for class-level dependencies, or in a particular method's parameter list, for more local dependencies.

Classes with implicit dependencies cost more to maintain than those with explicit dependencies.  They are more difficult to test because they are more tightly coupled to their collaborators.  They are more difficult to analyze for side effects, because the entire class's codebase must be searched for object instantiations or calls to static methods.  They are more brittle and more tightly coupled to their collaborators, resulting in more rigid and brittle designs.

Classes with explicit dependencies are more honest.  They state very clearly what they require in order to perform their particular function.  They tend to follow the Principle of Least Surprise by not affecting parts of the application they didn't explicitly demonstrate they needed to affect.  Explicit dependencies can easily be swapped out with other implementations, whether in production or during testing or debugging.  This makes them much easier to maintain and far more open to change.

The Explicit Dependencies Principle is closely related to the Dependency Inversion Principle and the Hollywood Principle.

Consider the PersonalizedResponse class in this Gist, which can be constructed without any dependencies:

Implicit Dependencies Example

1using System;
2using System.IO;
3using System.Linq;
4
5namespace ImplicitDependencies
6{
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 var customer = new Customer()
12 {
13 FavoriteColor = "Blue",
14 Title = "Mr.",
15 Fullname = "Steve Smith"
16 };
17 Context.CurrentCustomer = customer;
18
19 var response = new PersonalizedResponse();
20
21 Console.WriteLine(response.GetResponse());
22 Console.ReadLine();
23 }
24 }
25
26 public static class Context
27 {
28 public static Customer CurrentCustomer { get; set; }
29
30 public static void Log(string message)
31 {
32 using (StreamWriter logFile = new StreamWriter(
33 Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
34 "logfile.txt")))
35 {
36 logFile.WriteLine(message);
37 }
38 }
39 }
40
41 public class Customer
42 {
43 public string FavoriteColor { get; set; }
44 public string Title { get; set; }
45 public string Fullname { get; set; }
46 }
47
48 public class PersonalizedResponse
49 {
50 public string GetResponse()
51 {
52 Context.Log("Generating personalized response.");
53 string formatString = "Good {0}, {1} {2}! Would you like a {3} widget today?";
54 string timeOfDay = "afternoon";
55 if (DateTime.Now.Hour < 12)
56 {
57 timeOfDay = "morning";
58 }
59 if (DateTime.Now.Hour > 17)
60 {
61 timeOfDay = "evening";
62 }
63 return String.Format(formatString, timeOfDay,
64 Context.CurrentCustomer.Title,
65 Context.CurrentCustomer.Fullname,
66 Context.CurrentCustomer.FavoriteColor);
67 }
68 }
69}

This class is clearly tightly coupled to the file system and the system clock, as well as a particular customer instance via the global Context class.  If we were to refactor this class to make its dependencies explicit, it might look something like this:

Explicit Dependencies Example

1using System;
2using System.IO;
3using System.Linq;
4
5namespace ExplicitDependencies
6{
7 class Program
8 {
9 static void Main(string[] args)
10 {
11 var customer = new Customer()
12 {
13 FavoriteColor = "Blue",
14 Title = "Mr.",
15 Fullname = "Steve Smith"
16 };
17
18 var response = new PersonalizedResponse(new SimpleFileLogger(), new SystemDateTime());
19
20 Console.WriteLine(response.GetResponse(customer));
21 Console.ReadLine();
22 }
23 }
24
25 public interface ILogger
26 {
27 void Log(string message);
28 }
29
30 public class SimpleFileLogger : ILogger
31 {
32 public void Log(string message)
33 {
34 using (StreamWriter logFile = new StreamWriter(
35 Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
36 "logfile.txt")))
37 {
38 logFile.WriteLine(message);
39 }
40 }
41 }
42
43 public interface IDateTime
44 {
45 DateTime Now { get; }
46 }
47
48 public class SystemDateTime : IDateTime
49 {
50 public DateTime Now
51 {
52 get
53 {
54 return DateTime.Now;
55 }
56 }
57 }
58
59 public class Customer
60 {
61 public string FavoriteColor { get; set; }
62 public string Title { get; set; }
63 public string Fullname { get; set; }
64 }
65
66 public class PersonalizedResponse
67 {
68 private readonly ILogger _logger;
69
70 private readonly IDateTime _dateTime;
71
72 public PersonalizedResponse(ILogger logger,
73 IDateTime dateTime)
74 {
75 this._dateTime = dateTime;
76 this._logger = logger;
77 }
78
79 public string GetResponse(Customer customer)
80 {
81 _logger.Log("Generating personalized response.");
82 string formatString = "Good {0}, {1} {2}! Would you like a {3} widget today?";
83 string timeOfDay = "afternoon";
84 if (_dateTime.Now.Hour < 12)
85 {
86 timeOfDay = "morning";
87 }
88 if (_dateTime.Now.Hour > 17)
89 {
90 timeOfDay = "evening";
91 }
92 return String.Format(formatString, timeOfDay,
93 customer.Title,
94 customer.Fullname,
95 customer.FavoriteColor);
96 }
97 }
98}

In this case, the logging and time dependencies have been pulled into constructor parameters, while the customer being acted upon has been pulled into a method parameter.  The end result is code that can only be used when the things it needs have been provided for it (and whether you scope dependencies at the class or method level will depend on how they're used by the class, how many methods reference the item in question, etc. - both options are shown here even though in this case everything could simply have been provided as method parameters).

See Also

Dependency Inversion Principle

New Is Glue (Ardalis.com)

Edit this page on GitHub