2017年11月5日 星期日

Day2-10 Coupling and Cohesion 耦合和內聚力

5.1 Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits. 

好的設計會建議遵循loose coupling以及high cohesion(低耦合高內聚)。OO設計會希望能夠達成
  • Ease of Creation
  • Ease of Maintenance 
  • Ease of Enhancements
Coupling
class A對class B認識程度; class間如何互動
  • 若A只知道B暴露的interface,則為loose coupling (Good!)
  • 若A知道除了B暴露的interface以外的東西(包含有哪些instance variable),則為tight coupling (Bad!)
  • 若A依賴B class內的某個部份,則為tight coupling (Bad!)
  • 若A知道B如何implementation,則為tight coupling (Bad!)
  • 若A修改了和interface沒有關係的程式碼,卻影響到B,則為不好的設計(A可能根本不知道B用了A內部的東西)。如此的修改會造成B程式碼的破壞。
  • 若B封裝內的get, set method依賴A內的method,則為tight coupling (Bad!)
  • loose coupling將會有良好的encapsulation
理想上,OO系統內object的互動都應該要透過type的API(contract),而一個良好的API應該要有良好的encapsulation。

Cohesion
一個class擁有單一目標的程度
  • 一個class擁有越專精的目標,則為high cohesion (Good!)
  • 擁有high cohesion的class,越少被更動,越常被使用
範例:若今天有一旅程規劃系統,裡面需要有地圖功能,消費功能,行程功能
以下是將所有程式碼都寫在一個class

class TravelDesign{
    void MapDesign(){}
    void AcccountingRecord(){}
    void ScheduleDesign(){}
}
high cohesion的做法是將所有功能都切成一個class
class TravelDesign{}
class MapDesign{}
class AcccountingRecord{}
class ScheduleDesign{}
不如將所有class切出來,變成只做非常專門的工作,如此擁有high cohesion。

總結:
  • Encapsulation,它的重點和隱藏實作細節最相關
  • Polymorphism原則,它的重點是允許一個物件可以被看做多種型別
  • Coulping是 OO 原則,它的重點是確定類別只透過 API 和其他的類別溝通
  • Cohesion是 OO 原則,它的重點是確定類別只為單一、且定義精準的目地 

沒有留言:

張貼留言