Interface Segregation Principle

The Interface Segregation Principle (ISP) is one of the five SOLID principles of object-oriented design, first introduced by Robert C. Martin. It states that a client should not be forced to depend on methods that it does not use.

In other words, an interface should be segregated or split into smaller, more specific interfaces rather than one large, general-purpose interface. This helps to prevent clients from being burdened with unnecessary or irrelevant methods that they don’t need.

The goal of ISP is to promote high cohesion and low coupling. High cohesion means that the methods within an interface should be closely related and work together to achieve a specific purpose. Low coupling means that dependencies between components should be minimized to reduce the impact of changes and promote reusability.

Example

Let’s say we have an interface called Vehicle:

public interface Vehicle {
    void startEngine();
    void stopEngine();
    void accelerate();
    void brake();
    void changeGear();
    void turnLeft();
    void turnRight();
    void reverse();
}

This interface defines a set of methods for a vehicle. However, not all vehicles need to implement all of these methods. For example, a bicycle would not have an engine, so it does not need to implement startEngine() or stopEngine().

To follow the Interface Segregation Principle, we can break down the Vehicle interface into smaller, more focused interfaces. For example:

public interface MotorizedVehicle {
    void startEngine();
    void stopEngine();
    void accelerate();
    void brake();
    void changeGear();
}

public interface Steerable {
    void turnLeft();
    void turnRight();
}

public interface Reversable {
    void reverse();
}

Now, a Car class can implement MotorizedVehicle and Steerable, while a Bicycle class can implement Steerable only. This allows us to avoid forcing classes to implement unnecessary methods and ensures that interfaces are small, focused, and cohesive.