Interface Segregation Principle

Hicham BEN KACHOUD
3 min readApr 6, 2022

--

Introduction

Interface Segregation Principle is the fourth of SOLID principles about Object-Oriented Design presented by Uncle Bob. They are :

In this post, I will focus on ISP, and I will explain the other principles in future articles.

Definition

Uncle Bob defines the principle as:

Client should not be forced to depend upon interfaces that they don’t use.

You should make your interfaces as tight as possible so that you don’t force classes to implement behaviors they don’t need.

Implementing the ISP, you should change your large interfaces to make them more specific. Classes should only implement the methods they really need.
Otherwise, each modification in the large interface will crash classes that do not use the modified methods.

For example, we have two classes A & B that implement an interface I.

If we modify the interface I for class A we should also modify class B. So we have a problem of strong coupling between both classes and the interface.

Example

We will have an online buying system for cosmetic products and we suggest three payment categories: Installment, Cash & Online Payments.

IOrder.php

If you see the code above, you will notice that we have a large interface that handles all payment categories.

So we should implement this interface for the three paiment categories.

Look at the code bellow :

Implementations of IOrder

In the above code, there are three classes which implement the IOrder interface. Each class implements a single method and others are not useful, which violates the Interface Segregation Principle.

For a successful implementation of ISP, we need to reduce our large interface to several small interfaces.

Small interfaces

So, each class can implement the specific interface with the only useful method.

Implementations

We can now modify the IOrder interface to extend these interfaces.

IOrder interface

For now, we can have the Order main class that includes all three methods if we need to use all categories in certain contexts.

Order.php

Conclusion

The ISP lets you reduce your large interface to multiple small interfaces that your classes don’t implement behaviors you don’t need.

Thank you for reading this quick post. If you like the content feel free to follow me on my social media profiles. Thank you.

Twitter: https://twitter.com/HBenkachoud
Linkedin: https://www.linkedin.com/in/hicham-benkachoud/

--

--

Hicham BEN KACHOUD
Hicham BEN KACHOUD

No responses yet