DEV Community

Igor Irianto
Igor Irianto

Posted on • Edited on

7 1

Interface Segregation Principle

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
caruso profile image
Giuseppe Caruso

I see you are writing a series of articles on SOLID principles.
It would be great if you could implement at the top of your article the links to the series. Keep on writing!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more