Sobes.tech
Middle+

Tell us about the principle of interface segregation (Interface Segregation Principle).

sobes.tech AI

Answer from AI

The Interface Segregation Principle (ISP) states: clients should not depend on interfaces they do not use.

This means that instead of creating one large interface with many methods, it is better to create several smaller and more specific interfaces. Each client should implement only the interfaces that are truly necessary for it.

Advantages of following ISP:

  • Reduced coupling: Changes in one method of a large interface do not affect clients that do not use that method.
  • More flexible code: It is easier to add new implementations since they are only required to implement the necessary interfaces.
  • Improved readability: Code becomes clearer when interfaces clearly define specific responsibilities.

Example:

Instead of:

interface Worker {
    void work();
    void eat();
    void sleep();
}

Better:

interface Workable {
    void work();
}

interface Eatable {
    void eat();
}

interface Sleepable {
    void sleep();
}

Then the HumanWorker class can implement all three:

class HumanWorker implements Workable, Eatable, Sleepable {
    @Override
    public void work() {
        // ...
    }

    @Override
    public void eat() {
        // ...
    }

    @Override
    public void sleep() {
        // ...
    }
}

And some RobotWorker only implements Workable:

class RobotWorker implements Workable {
    @Override
    public void work() {
        // ...
    }
}