🪨 SOLID Principles
SOLID is a list of 5 software engineering principles. It is a meta acronym where each letter corresponds to another acronym:
- SRP: Single Responsibility Principle
- OCP: Open-Closed Principle
- LSP: Liskov Substitution Principle
- ISP: Interface Segregation Principle
- DIP: Dependency Inversion Principle
Without any further ado, let's jump into today's topic:
Interface Segregation Principle (ISP)
Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented programming.
An interface should have a specific, well-defined purpose, and clients should only be required to implement the methods that are relevant to their needs. Clients should not be forced to depend on interfaces they do not use.
Goal: The aim is to make software design more modular and flexible by avoiding the creation of large, monolithic interfaces that compel clients to implement unnecessary methods.
- Encourage the use of smaller, client-specific interfaces.
- Decreases coupling by preventing clients from relying on unnecessary methods, which, in turn, reduces the connection between classes and interfaces.
- Enhances modularity by designing smaller, focused interfaces that make it easier to understand and maintain the code.
- Improves reusability as clients can implement only the interfaces and methods relevant to their specific context, thus promoting code reusability.
- Simplifies testing through narrowly-focused interfaces, allowing clients to test only the methods directly associated with their functionality.
Bad Example:
interface Worker {
public function work();
public function eat();
}
Here, we have a single interface, Worker
, that includes two methods: work
and eat
. If a class needs to implement this interface but doesn't require both methods, it will be forced to provide empty implementations or methods with no meaningful behavior, violating the ISP.
Good Example:
interface Workable {
public function work();
}
interface Eatable {
public function eat();
}
Here, we've segregated the original Worker
interface into two smaller, focused interfaces: Workable
and Eatable
. Now, classes can choose to implement one or both interfaces based on their specific needs. This adheres to the Interface Segregation Principle, promoting better code design and flexibility.
Top comments (0)