C++ Coding Standards Item 5 : Give One entity one cohesive responsibility

来源:互联网 发布:c语言空格怎么 编辑:程序博客网 时间:2024/04/30 23:37

http://spaces.msn.com/members/spiritauding/Blog/cns!1psm74keJLzaQ6CnZ_EB1mAw!120.entry

C++ Coding Standards Item 5 : Give One entity one cohesive responsibility
Summary

Focus on one thing at a time: Prefer to give each entity (variable, class, function, namespace, module, library) one well-defined responsibility. As an entity grows, its scope of responsibility naturally increases, but its responsibility should not diverge.

同一时间只关注一件事情:最好给每一个实体(variable, class, function, namespace, module, library)一个明确的职责。当实体增长(扩展,怎么翻译好一点?)的时候,它的职责范围自然的扩大了,但是它的职责不应该有不同的发展方向。


Discussion
A good business idea, they say, can be explained in one sentence. Similarly, each program entity should have one clear purpose.

一个好的商业计划可以用一句话说明。类似的,一个好的程序实体应该有一个清楚地目的。


这条规则主要讲有很多功能(职责)的实体,它们通常很难设计,用起来也很困难,所以,还是让我们的实体(class,function……)目的单一些,单纯一点好。


Prefer to build higher-level abstractions from smaller lower-level abstractions. Avoid collecting several low-level abstractions into a larger low-level conglomerate. Implementing a complex behavior out of several simple ones is easier than the reverse.

最好在比较小的低级别的抽象基础上建立高级别的抽象。避免把许多小的低级别抽象聚合到一个大的低级别的抽象中。相对而言,通过几个简单的实体实现一个复杂的行为,要比通过一个实体来实现简单的多。(这句话好难讲!!)



Examples
Example 1: realloc. In Standard C, realloc is an infamous example of bad design. It has to do too many things: allocate memory if passed NULL, free it if passed a zero size, reallocate it in place if it can, or move memory around if it cannot. It is not easily extensible. It is widely viewed as a shortsighted design failure.

Example 1 讲的是标准C语言中的realloc函数,realloc必须要做太多的事情了:传入NULL的话就分配内存,传入0值得话就释放内存,如果在那个地方(程序执行点)可以realloc的话,就正常的工作,否则就要做内存移动……。而且不能很容易的扩展。基本上都认为它(realloc)的设计是很失败的。

Example 2: basic_string. In Standard C++, std::basic_string is an equally infamous example of monolithic class design. Too many "nice-to-have" features were added to a bloated class that tries to be a container but isn't quite, is undecided on iteration vs. indexing, and gratuitously duplicates many standard algorithms while leaving little space for extensibility. (See Item 44's Example.)

Example 2:basic_string.又一个在单一功能的类的设计中的反面例子,它的“罪过”我就不逐句翻译了,大家读原文也能清楚。


这章讲述的内容比较简单,以前我总是注意不到,或者说在刻意的违反,总是希望一个类可以做这个也可以做那个,呵呵,记得我曾经把几个功能函数全部写在一个 CPP文件中,无论从程序设计角度还是文学欣赏的角度看,那个文件都极度的不具备可读性,所以它也从我的历史中永久的消失了……


Copy Left (C) Scorpio Auding