心法
又稱迪米特法則。
高階模組不應該知道低階模組的內部如何運作 。
低階模組不應該暴露內部物件,不應該暴露實踐細節,應僅提供方法給高階模組使用。
不必要的公開方法就設為 private 或 protected。
範例
<?php class CartController { public function checkout($sn, $payment, $shipment) { $order = new Order($sn); $order->setPayment($payment); $order->setShipment($shipment); if ($order->save()) { $order->sendMail(); } } }
程式中透露出低端物件order做了哪些事,違反了最小知識原則低階模組不應該暴露內部物件,不應該暴露實踐細節。
解決方式(最小知識)
<?php class Order { public function checkout($payment, $shipment) { $this->setPayment($payment); $this->setShipment($shipment); if ($this->save()) { $this->sendMail(); } } } class CartController { public function checkout($payment, $shipment) { $order = new Order($sn); $order->checkout($payment, $shipment); } }
現在Order物件只提供checkout方法,CartController完全不必理會Order到底做了哪些事情。這代表著CartController與Order之間的耦合關係減少了。
遵守介最小知識好處
違反最小知識原則,代表使用者需知道該物件很多細節才可以使用你的API,讓API變得難用。
一旦流程有所變動,就須更改高端物件的程式,增加了維護上的困難。
相關文章:
- PHP物件導向 – 三大特性:封裝(Encapsulation)、繼承(Inheritance)、多型(Polymorphism)
- PHP物件導向 – 單一職責(Single Responsibility Principle, SRP)
- PHP物件導向 – 開放封閉(Open Closed Principle, OCP)
- PHP物件導向 – 里氏替換(Liskov Substitution Principle, LSP)
- PHP物件導向 – 最小知識(Least Knowledge Principle, LKP)
- PHP物件導向 – 介面隔離(Interface Segregation Principle, ISP)
- PHP物件導向 – 依賴反轉(Dependency-Inversion Principle, DIP)