Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Interface Segregation Principle (ISP)

1. Introduction

The Interface Segregation Principle is one of the five SOLID principles of object-oriented programming and design. It states that no client should be forced to depend on methods it does not use. This principle encourages the creation of smaller, more focused interfaces instead of large, general-purpose ones.

2. Key Concepts

Definition

The ISP encourages developers to create multiple, specific interfaces rather than a single, general-purpose interface. This way, clients only need to know about the methods that are relevant to them.

Note: Adhering to this principle improves system maintainability and flexibility.

3. Best Practices

  • Design interfaces to be client-specific.
  • Use multiple interfaces for different client needs.
  • Avoid "fat" interfaces that include unnecessary methods.
  • Refactor large interfaces into smaller ones as needed.

4. Code Example


interface Printer { void print(Document doc); } interface Scanner { void scan(Document doc); } class MultiFunctionPrinter implements Printer, Scanner { public void print(Document doc) { // Print implementation } public void scan(Document doc) { // Scan implementation } } class SimplePrinter implements Printer { public void print(Document doc) { // Print implementation } }

In this example, we have separated the functionalities into two interfaces: Printer and Scanner. The MultiFunctionPrinter implements both, while the SimplePrinter only implements the Printer interface, adhering to the ISP.

5. FAQ

What happens if I don’t follow the ISP?

If you don’t follow the ISP, clients may end up with unused methods, which can lead to confusion, increased complexity, and a greater chance of errors in the codebase.

How do I know when to create a new interface?

If you find that a client is only using a subset of methods from an interface, it may be a sign that you should create a new, more focused interface.