8. 你會寫出這種程式碼嗎?小心違反「最少知識原則」!

2023年12月27日

💎 加入 E+ 成長計畫 與超過 350+ 位軟體工程師一同在社群中成長,並且獲得更多的軟體工程學習資源

你會寫出這種程式碼嗎?小心違反「最少知識原則」!

程式碼先上:

class Address:
 def get_country(self):
  return "Some Country"
class Person:
 def get_address(self):
  return Address()
class Company:
 def get_ceo(self):
  return Person()
company = Company()
country = company.get_ceo().get_address().get_country()

以上這樣的做法違反了 The Law of Demeter ,這法則也被稱為「最少知識的原則」,他的思想是,class 彼此之間要盡可能的少了解,class 可以調用自己的方法,但不要調用「朋友」的方法,就像上面這樣。

可以改進成這樣:

class Company:
 def get_ceo(self):
  return Person()
def get_ceo_country(self):
  return self.get_ceo().get_address().get_country()
company = Company()
country = company.get_ceo_country()

看似只是把 .get_ceo().get_address().get_country() 拉到 class 當中,但其實就增加了他的封裝性,也就是說減少類與類之間的理解,當你在用 Company 類時,無需知道其他事情。

The Law of Demeter 的好處是:

  1. 降低耦合度:減少 class 之間的交互,有助於降低耦合性。
  2. 增强封装性:LoD 鼓勵隱藏 class 內部的複雜性,只通過必要接口與外部互動。
  3. 提高可讀性:每個職責被劃分清楚,程式碼可讀性能提升。
🧵 如果你想收到最即時的內容更新,可以在 FacebookInstagram 上追蹤我們