- Modular Programming with PHP 7
- Branko Ajzele
- 338字
- 2021-07-14 10:06:01
Interface Segregation Principle
The Interface Segregation Principle states that clients should only implement interfaces they actually use. They should not be forced to implement interfaces they do not use. As per the definition found on Wikipedia:
"many client-specific interfaces are better than one general-purpose interface"
What this means is that we should split large and fat interfaces into several small and lighter ones, segregating it so that smaller interfaces are based on groups of methods, each serving one specific functionality.
Let's take a look at the following leaky abstraction that violates the ISP:
interface Appliance { public function powerOn(); public function powerOff(); public function bake(); public function mix(); public function wash(); } class Oven implements Appliance { public function powerOn() { /* Implement ... */ } public function powerOff() { /* Implement ... */ } public function bake() { /* Implement... */ } public function mix() { /* Nothing to implement ... */ } public function wash() { /* Cannot implement... */ } } class Mixer implements Appliance { public function powerOn() { /* Implement... */ } public function powerOff() { /* Implement... */ } public function bake() { /* Cannot implement... */ } public function mix() { /* Implement... */ } public function wash() { /* Cannot implement... */ } } class WashingMachine implements Appliance { public function powerOn() { /* Implement... */ } public function powerOff() { /* Implement... */ } public function bake() { /* Cannot implement... */ } public function mix() { /* Cannot implement... */ } public function wash() { /* Implement... */ } }
Here we have an interface setting requirements for several appliance related methods. Then we have several classes implementing that interface. The problem is quite obvious; not all appliances can be squeezed into the same interface. It makes no sense for a washing machine to be forced to implement bake and mix methods. These methods need to be split each into its own interface. That way concrete appliance classes get to implement only the methods that actually make sense.