Interface Segregation Principle

April 7, 2021

Interface Segregation Principle

The Interface Segregation Principle states that your interfaces should not force the client to implement the methods they don't actually need.

For an example, suppose that you have a Dinner (pseudo) class:

class Dinner
  meat() { // serve meat }
  veggies() { // serve veggies }
  dessert() { // serve dessert }

Later you want to extend it to create Japanese and Vegan foods.

class Japanese inherits Dinner
  meat() { ... }
  veggies() { ... }
  dessert() { ... }

class Vegan inherits Dinner
  meat() { // uh oh, no meat here - throw error or noop }
  veggies() { ... }
  dessert() { ... }

With the way the Dinner class is implemented, it comes with the meat method, even though the Vegan users will never use it (they will have to implement some sort of noop procedure on the meat method). Forcing users to use unused methods is not a good practice. It is a violation to the Interface Segregation Principle.

One way to solve this is to maybe split the parent class:

class Meat
  meat() { ... }

class Salad
  veggies() { ... }

class Dessert
  dessert() { ... }

Now when you want to create a Japanese dinner dish having meat and veggies, you can use them as modules:

class Japanese
  include Meat
  include Salad
  include Dessert

Now you can just implement a Vegan class with only the necessary modules.

class Vegan
  include Salad
  include Dessert

Using this approach, your dinner classes are loosely coupled. None of the classes are forced to use methods they will never use.