SOLID, Part 1: Single Responsibility Principle


| December 14, 2017 | in

SOLID is an acronym created by Robert Martin (Uncle Bob) to describe five principles we should follow to make software designs more understandable, flexible, and maintainable. In general, these are very good guidance.

While I don’t think the acronym is perfect and I don’t really focus on the open / closed principle, I do think SOLID is a set of well-known and helpful concepts to keep in mind when writing software.

In this series, I will quickly jump into each of these five principles and how they apply to writing software. We will focus on how these principles can be applied when developing with Angular, or at least how I would use them.

In this post, I am covering the “S” in SOLID, which stands for “single responsibility principle”.

I define “single responsibility principle” (SRP) as creating a single module that has single reason to change. This differs from how others describe SRP.

Some will say that SRP involves having a single module within a single purpose. The “single reason to change” definition of SRP is similar to “single purpose”, but not exactly the same. With “single reason to change”, we are hopefully doing a better job of future proofing our applications.

Now to the examples.

Here is a “single purpose” example of a TypeScript Service that serves two masters:

  • Saving and loading data from an HTTP endpoint, which is used to save and load cart data for an ecommerce system.
  • Calculating the cart total and validating the cart.

The cart’s accessor is doing a lot. It has a lot of reasons to change.

In the example below, we break out the service into three pieces, thus following the “single reason to change” definition:

  • Interaction with the HTTP endpoint to save and load the cart.
  • Calculation of the cart price.
  • Validation of the cart.

Each piece should feel more focused.

Hopefully when we further break down our code into pieces that have a single reason to change, we will end up with code that is easier to read and easier to maintain.

This is just one example of how we architect our software at Don’t Panic Labs. We do volatility-based decomposition and want each module to be a boundary of change. That means we want a given module to have a single reason to change, hence my definition of SRP.

Related posts