DEV Community

loading...

Interface Segregation Principle

iggredible profile image Igor Irianto ・1 min read

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 }
Enter fullscreen mode Exit fullscreen mode

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() { ... }
Enter fullscreen mode Exit fullscreen mode

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() { ... }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

class Vegan
  include Salad
  include Dessert
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)

pic
Editor guide