Codacoda
Back to Academy

coding principles

Interface Segregation Principle

The Interface Segregation Principle (ISP) states that no client should be forced to depend on methods it does not use. Large, monolithic interfaces should be split into smaller, more specific ones so that implementing classes only need to know about the methods that are relevant to them. This prevents 'fat interfaces' that couple unrelated concerns and force implementers to provide stub or no-op implementations for methods they do not need.

Use Cases

  • Breaking a large repository interface into read and write sub-interfaces
  • Designing event handler contracts where listeners only subscribe to events they care about
  • Creating role-based interfaces (e.g., Printable, Serializable) instead of one all-encompassing interface
  • Microservice APIs that expose fine-grained endpoints rather than a single do-everything endpoint

Visualization

BEFORE«interface» Workerwork()eat()sleep()HumanWorkerwork()eat()sleep()RobotWorkerwork()eat() ??sleep() ??
Speed:1x
A single Worker interface forces all implementers to define work(), eat(), and sleep() — even when not all methods apply.Step 1 / 7

Implementation

Output

Click "Run Code" to see output...