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


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
發佈了55 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章