Skip to main content

Ch13: 元件內聚性 (Component Cohesion)

Chapter outline:

  • REP: The Reuse/Release Equivalence Principle
  • CCP: The Common Closure Principle
  • CRP: The Common Reuse Principle

REP: The Reuse/Relase Equivalence Principle

The granular of reuse is the granular of release.

元件復用的最小粒度等於發布的最小粒度

tip

腦力激盪: 你期望一個能夠復用或發佈出來的 module 要包含哪些東西呢?


期望:

  • 版本號
  • 釋出時要有 release note
  • 文件
  • 維護
  • 預測性
    • 我在使用的 module 不會被改動
    • 要改動的話要通知我
    • 我可以選擇舊版還是新版

組成再一起的 classes 跟 modules 應該是能一起釋出的,而綁在一起的情況應該對使用者還有作者來說都是合理的, 講合理可能是一個比較弱的建議,但是當我們遇到"不合理"時,應該很容易能夠察覺

CCP: The Common Closure Principle

Gather into components those classes that change for the same reasons and at the same times. Separate into different components those classes that change at different times and for different reasons.

Recap: 什麼是 Single Responsibility Principle?

CCP 原則就是 component 版本的 SRP, i.e., 把 SRP 原則中的 class 替換成 component

e.g., 所有管 Database 的 class 組成同一個 Component,所有管商業邏輯組成同一個 Component

REP 跟 CCP 有些許衝突,REP 告訴我們做成一個可發佈版本,但這可能會需要引入更多不同功能, 而 CCP 則告訴我們功能相近的組合成一個 Component,如果功能不相近則應該分成不同 Component

CRP: The Common Reuse Principle

Don’t force users of a component to depend on things they don’t need.

在同個 Component 裡的 Class,我們預期他們會有很多相依性

Recap: 什麼是 Interface Segregation Principle (ISP) 原則

跟 ISP 的關係: CRP 是比 ISP 更廣的版本,ISP 建議不要依賴在 class 中用不到的 methods, CRP 建議不要依賴 Component 中用不到的 classes

CRP 原則速記法: 不要依賴用不到的東西!

The Tension Diagram for Component cohesion

REP 跟 CCP 是關於包含的原則,會讓 Components 變大, CRP 則是關於捨去的原則,會驅使 Components 變小

架構師必須在三個原則中做取捨 Figure 13.1 Cohesion principles tension diagram

例如項目早期 CCP > REP,因為這一階段,研發速度比復用性重要 一般來說,項目的重心會從三角形的右側,產品成熟之後,開始偏向左側

結論: REP, CCP, CRP 這些原則的調整是動態的,今年適用的劃分可能明年就不能用了