(翻译)C#中的SOLID原则 – 单一责任原则

The SOLID Principles in C# — Single Responsibility

原文链接:http://www.remondo.net/solid-principles-csharp-single-responsibility/

For us developers S.O.L.I.D. is a five letter acronym with each letter pointing to a basic principle of good Object Oriented Design. The principle set was introduced almost twenty years ago by Robert C. Martin (Uncle Bob), a well known author, speaker and thinker on the subject. In this series we discuss each principle with some practical code examples.

对美帝的软件开发者来说,S.O.L.I.D 是五个单词的首字母缩写,其中每个字母代表了面向对象编程世界中的一项基本准则。这些准则在大概20年以前由Robert C. Martin提出。Robert C. Martin先生是知名的畅销书作者,演讲者,同时也是行业的思考家。在本系列中文章中,我们将用一些实际代码来讨论S.O.L.I.D中的每一项开发准则。

The first post in the SOLID by Example series deals with the Single Responsibility Principle (SRP). This is the notion that an object should have only a single responsibility. Uncle Bob defines a responsibility to be ‘a reason for change’. The more responsibilities a class has, the more change can be expected. The more expected change, the more likely is the introduction of bugs. Changes to one responsibility can have an impact on other responsibilities.

S.O.L.I.D示例代码系列的第一篇文章我们先来看看单一责任原则(SRP)。通俗的讲,单一责任指的是一个对象应该仅负责一项工作。Robert C. Martin将其理解为一个对象应该仅有一个能够引起其变化的原因。一个类承载的责任越多,引起其变化的原因也就越多,引起其变化的原因越多,引入Bug的可能性也就越大。修改其中的一个责任点,极有可能会对其它的责任点产生影响。

In this example we create a Radio class with some common operations. We can turn the volume up or down and change the station. Here is one way we could implement this class.

在示例代码中,我们将新建一个Radio类,添加一些常用的操作。这些操作包括音量调高或调低,换台等。下面是实现这个类的一种方式:

One could argue that the Radio class has two responsibilities, being volume and station management. These operations will be called from completely different areas of the client using it. Changes can occur whenever we want to modify some of the volume- or station management logic. By separating these responsibilities into distinct classes, we can avoid breakage in other parts of our class when our code meets a new requirement. The class design could end up like this:

值得商榷的是,上述的Radio类拥有两个职责:音量调整和频道管理。这些操作将会被所处地域完全不同的客户调用。当我们意图修改音量调整或频道管理方面的逻辑时,改变就不可避免的发生了。通过将这些职责分拆到不同的类中,当我们的代码需要添加一个新的需求时,此举能够避免破坏类中的其它部分。最终该类的设计如下:

 

Now this design still does violate other SOLID principles, but it is just to make the Single Responsibility point clear. The class design greatly improves re-usability and maintainability. It’s more loosely coupled and clean. It’s also better testable. Changes to one responsibility does not have an impact on the rest of the design.

当然,上面的设计仅仅是对单一职责原则进行一个清楚的说明,其仍然违反了其它的S.O.L.I.D准则。该类的设计极大的提高了代码的复用性和可维护性,降低了类之间的偶合,并且更容易进行测试。同时,重构为单一职责之后,不会对其它的设计产生负面影响。

posted @ 2012-11-06 10:39  麦克默菲  阅读(455)  评论(0编辑  收藏  举报