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

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:

 

namespace ImplicitDependencies
{
class Program
{
static void Main(string[] args)
{
var customer = new Customer()
{
FavoriteColor = "Blue",
Title = "Mr.",
Fullname = "Steve Smith"
};
Context.CurrentCustomer = customer; var response = new PersonalizedResponse(); Console.WriteLine(response.GetResponse());
Console.ReadLine();
}
} public static class Context
{
public static Customer CurrentCustomer { get; set; } public static void Log(string message)
{
using (StreamWriter logFile = new StreamWriter(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"logfile.txt")))
{
logFile.WriteLine(message);
}
}
} public class Customer
{
public string FavoriteColor { get; set; }
public string Title { get; set; }
public string Fullname { get; set; }
} public class PersonalizedResponse
{
public string GetResponse()
{
Context.Log("Generating personalized response.");//a particular Log instance via the global Context class
string formatString = "Good {0}, {1} {2}! Would you like a {3} widget today?";
string timeOfDay = "afternoon";
if (DateTime.Now.Hour < 12)// the system clock
{
timeOfDay = "morning";
}
if (DateTime.Now.Hour > 17)
{
timeOfDay = "evening";
}
return String.Format(formatString, timeOfDay,
Context.CurrentCustomer.Title, //a particular customer instance via the global Context class
Context.CurrentCustomer.Fullname,
Context.CurrentCustomer.FavoriteColor);
}
}
}

  

  

Explicit Dependencies Example

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).

using System;
using System.IO;
using System.Linq; namespace ExplicitDependencies
{
class Program
{
static void Main(string[] args)
{
var customer = new Customer()
{
FavoriteColor = "Blue",
Title = "Mr.",
Fullname = "Steve Smith"
}; var response = new PersonalizedResponse(new SimpleFileLogger(), new SystemDateTime());//class constructor Console.WriteLine(response.GetResponse(customer));//method parameters
Console.ReadLine();
}
} public interface ILogger
{
void Log(string message);
} public class SimpleFileLogger : ILogger
{
public void Log(string message)
{
using (StreamWriter logFile = new StreamWriter(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"logfile.txt")))
{
logFile.WriteLine(message);
}
}
} public interface IDateTime
{
DateTime Now { get; }
} public class SystemDateTime : IDateTime
{
public DateTime Now
{
get
{
return DateTime.Now;
}
}
} public class Customer
{
public string FavoriteColor { get; set; }
public string Title { get; set; }
public string Fullname { get; set; }
} public class PersonalizedResponse
{
private readonly ILogger _logger; private readonly IDateTime _dateTime; public PersonalizedResponse(ILogger logger,
IDateTime dateTime)//class constructor
{
this._dateTime = dateTime;
this._logger = logger;
} public string GetResponse(Customer customer)//method parameters
{
_logger.Log("Generating personalized response.");
string formatString = "Good {0}, {1} {2}! Would you like a {3} widget today?";
string timeOfDay = "afternoon";
if (_dateTime.Now.Hour < 12)
{
timeOfDay = "morning";
}
if (_dateTime.Now.Hour > 17)
{
timeOfDay = "evening";
}
return String.Format(formatString, timeOfDay,
customer.Title,
customer.Fullname,
customer.FavoriteColor);
}
}
}

  

See Also

//a particular customer instance via the global Context class

编码原则 之 Explicit Dependencies Principle的更多相关文章

  1. 编码原则 之 Stable Dependencies

    The Stable Dependencies Principle states that “The dependencies between software packages should be ...

  2. S.O.L.I.D 是面向对象设计(OOD)和面向对象编程(OOP)中的几个重要编码原则

    注:以下图片均来自<如何向妻子解释OOD>译文链接:http://www.cnblogs.com/niyw/archive/2011/01/25/1940603.html      < ...

  3. 开放封闭原则(Open Closed Principle)

    在面向对象的设计中有很多流行的思想,比如说 "所有的成员变量都应该设置为私有(Private)","要避免使用全局变量(Global Variables)",& ...

  4. 最少知识原则(Least Knowledge Principle)

    最少知识原则(Least Knowledge Principle),或者称迪米特法则(Law of Demeter),是一种面向对象程序设计的指导原则,它描述了一种保持代码松耦合的策略.其可简单的归纳 ...

  5. 接口分离原则(Interface Segregation Principle)

    接口分离原则(Interface Segregation Principle)用于处理胖接口(fat interface)所带来的问题.如果类的接口定义暴露了过多的行为,则说明这个类的接口定义内聚程度 ...

  6. 依赖倒置原则(Dependency Inversion Principle)

    很多软件工程师都多少在处理 "Bad Design"时有一些痛苦的经历.如果发现这些 "Bad Design" 的始作俑者就是我们自己时,那感觉就更糟糕了.那么 ...

  7. 里氏替换原则(Liskov Substitution Principle)

    开放封闭原则(Open Closed Principle)是构建可维护性和可重用性代码的基础.它强调设计良好的代码可以不通过修改而扩展,新的功能通过添加新的代码来实现,而不需要更改已有的可工作的代码. ...

  8. 单一职责原则(Single Responsibility Principle)

    单一职责原则(SRP:The Single Responsibility Principle) 一个类应该有且只有一个变化的原因. There should never be more than on ...

  9. 【设计原则和编程技巧】单一职责原则 (Single Responsibility Principle, SRP)

    单一职责原则 (Single Responsibility Principle, SRP) 单一职责原则在设计模式中常被定义为“一个类应该只有一个发生变化的原因”,若我们有两个动机去改写一个方法,那这 ...

随机推荐

  1. common lisp里的几个操作符

    setf  赋值操作符,定义一个全局变量.返回值是最后一个赋值的结果. let 局部变量操作符.let表达式有两部分组成.第一部分是任意多的变量赋值,他们被包裹在一个()中,第二部分是任意数量的表示式 ...

  2. 13.vue组件

    vue组件(一) 组件嵌套: 1.全局嵌套: <!doctype html> <html> <head> <meta charset="utf-8& ...

  3. 11.vue 数据交互

    vue new Vue({ el,选择器 string/obj 不能选择html/body data, methods, template string/obj //生命周期 -- 虚拟DOM 1.初 ...

  4. STL next_permutation 算法原理和自行实现

    目标 STL中的next_permutation 函数和 prev_permutation 两个函数提供了对于一个特定排列P,求出其后一个排列P+1和前一个排列P-1的功能. 这里我们以next_pe ...

  5. WinDbg 之 SOS扩展命令

    SOS.dll (SOS debugging extension) The SOS Debugging Extension (SOS.dll) helps you debug managed prog ...

  6. 【转】Windows下Python快速解决error: Unable to find vcvarsall.bat

    转自:http://blog.csdn.net/sad_sugar/article/details/73743863 系统配置:Windows10 x64, Visual Studio 2017, P ...

  7. 使用spring data solr 实现搜索关键字高亮显示

    后端实现: @Service public class ItemSearchServiceImpl implements ItemSearchService { @Autowired private ...

  8. python练习题-day13

    1.获取移动平均值 def wrapper(fun): def inner(*args,**kwargs): ret=fun(*args,**kwargs) ret.__next__() return ...

  9. Failed to load driver class com.mysql.jdbc.Driver from HikariConfig class classloader sun.misc.Launcher$AppClassLoader@18b4aac2

    1.错误日志 Failed to load driver class com.mysql.jdbc.Driver from HikariConfig class classloader sun.mis ...

  10. Cutterman - 最好用的切图工具

    Cutterman - 最好用的切图工具 http://www.cutterman.cn/zh/cutterman