0% completed
The Interface Segregation Principle (ISP) focuses on ensuring that classes only implement interfaces they actually need. When a class is forced to implement methods it doesn’t use, it violates ISP. Let’s look at different techniques to identify ISP violations with examples.
1. Low Cohesion
Low cohesion happens when a class tries to handle multiple unrelated tasks, making the class less focused and harder to maintain. Low cohesion often leads to ISP violations because the class implements more methods than necessary.
Example
Here, MediaDevice
tries to handle both playing and recording, which can create low cohesion for a device that only plays media but doesn’t record.
2. Fat Interface
A fat interface is one that contains too many methods, usually covering multiple unrelated functionalities. Fat interfaces force classes to depend on methods they don’t need, leading to bloated code and ISP violations.
Example: Payment Interface
This interface is too large and covers different types of payment methods. It forces all classes implementing it to handle multiple payment options, even if they don’t need them.
3. Empty or Unsupported Methods
When classes implement an interface and include empty or unsupported methods, it’s a clear sign of an ISP violation. Classes should not be forced to implement methods they won’t use.
Example: Vehicle Interface
Here, the Car class has to implement fly() and sail(), even though these methods don’t make sense for a car. These methods either remain empty or throw exceptions, violating ISP.
In this case, a Vehicle
interface tries to cover driving, flying, and sailing, but not all vehicles can perform all these actions.
4. Classes with Too Many Responsibilities
When a class has too many responsibilities, it often implements multiple methods from a large interface. This indicates that the interface may need to be broken into smaller ones.
Example: Employee Interface
Here, CustomerSupport should only handle customer queries, but the large interface forces it to implement salary and team management methods, violating ISP.
The Interface Segregation Principle ensures that classes remain focused by only implementing the methods they need. By looking for signs such as low cohesion, fat interfaces, empty methods, and difficult testing scenarios, you can identify ISP violations early and refactor your code to maintain modular, flexible design.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible