Single Responsibility Principle

EDIT(2021/03/13): Old repositories didn’t bring me joy anymore, so the code examples are missing because I tossed them away…without realizing that this post needed them.

A class should have only one reason to change.

A class should have encapsulated a single part (responsibility) of the whole functionality. If not, that class is more susceptible to change and also its responsibilities are most likely to be coupled.

[pastacode lang=”java” user=”nluaces@gmail.com” repos=”https://github.com/nluaces/portfolio” path_id=”/src/main/java/io/nluaces/design/principles/srp/Notification.java” revision=”” highlight=”” lines=”” provider=”github”/]

The Notification class (and the other ones that use it), must change if:

  • It’s necessary use other protocol to create a notification besides email.
  • It’s necessary use other method to build content such as templates.
  • It’s necessary change how we export the message.
  • It’s necessary a method to retrieve sent emails in order to resend them.

A better approach may be this one:

[pastacode lang=”java” user=”nluaces@gmail.com” repos=”https://github.com/nluaces/portfolio” path_id=”/src/main/java/io/nluaces/design/principles/srp/Message.java” revision=”” highlight=”” lines=”” provider=”github”/]

The classes which implement this interface are the ones responsible for the content: how to construct it (with a class which implements MessageBuilder) and how to export it (with a class which implements ExportBuilder).

[pastacode lang=”java” user=”nluaces@gmail.com” repos=”https://github.com/nluaces/portfolio” path_id=”/src/main/java/io/nluaces/design/principles/srp/NotificationEvent.java” revision=”” highlight=”” lines=”” provider=”github”/]

The class NotificationEvent connect the message sent, protocol used, sender and receivers. This class is useful to resend messages or audit data.

[pastacode lang=”java” user=”nluaces@gmail.com” repos=”https://github.com/nluaces/portfolio” path_id=”/src/main/java/io/nluaces/design/principles/srp/NotificationService.java” revision=”” highlight=”” lines=”” provider=”github”/]

This class encapsulates all the actions that a notification service is responsible for.

As a draft, we can observe an example without using the principle and the better approach:

[pastacode lang=”java” user=”nluaces@gmail.com” repos=”https://github.com/nluaces/portfolio” path_id=”/src/main/java/io/nluaces/design/principles/srp/SingleResponsibilityPrinciple.java” revision=”” highlight=”” lines=”” provider=”github”/]