SOLID Principles in 59 Seconds

I — Interface Segregation Principle

4 of 5
The principle

Clients should not be forced to depend on interfaces they do not use.

A broad interface can make clients depend on methods they never use. Smaller interfaces let each client depend only on the operations it needs.

The channel interface requires sending, scheduling, and tracking methods, but EmailSender only sends messages. It must implement the other methods just to satisfy the interface, even though those methods throw errors.

Language

Original code

interface NotificationChannel {
  send(message: string): void
  schedule(message: string, at: Date): void
  track(id: string): string
}

class EmailSender implements NotificationChannel {
  send(message: string) {
    emailApi.send(message)
  }
  schedule(message: string, at: Date) {
    throw new Error('Not supported')
  }
  track(id: string) {
    throw new Error('Not supported')
  }
}

Revised code

interface Sender {
  send(message: string): void
}

interface Scheduler {
  schedule(message: string, at: Date): void
}

interface Tracker {
  track(id: string): string
}

class EmailSender implements Sender {
  send(message: string) {
    emailApi.send(message)
  }
}