SOLID Principles in 59 Seconds

S — Single Responsibility Principle

1 of 5
The principle

A class should have one, and only one, reason to change.

When a class combines unrelated responsibilities, changes to either one require editing that class. Separating them lets each class have one reason to change.

NotificationService writes the shipping message and sends the email. Changing the message or the email provider would require editing the same class, even though those changes come from different requirements.

Language

Original code

class NotificationService {
  sendShipped(orderId: string, email: string) {
    // Build the shipping message.
    const text = 'Order ' + orderId + ' shipped'
    // Send it through the email provider.
    emailApi.send(email, text)
  }
}

Revised code

// Message wording changes here.
function shippingMessage(orderId: string) {
  return 'Order ' + orderId + ' shipped'
}

// Email provider integration changes here.
class EmailSender {
  send(email: string, text: string) {
    emailApi.send(email, text)
  }
}

class NotificationService {
  sendShipped(orderId: string, email: string) {
    new EmailSender().send(email, shippingMessage(orderId))
  }
}