SOLID Design Principles

Single Responsibility Principle (SRP)

The Single Responsibility Principle states that “a class should only have one reason to change”, i.e. a class should do one thing, not several.

Some ideas behind SRP:

  • A change to a program spec requires a change to the source code.
  • If changes to different parts of the spec require changes in the same class, then SRP is violated.

Primeagen talks about this https://www.youtube.com/watch?v=TT_RLWmIsbY

  • Locality of behavior vs. Single responsability principle
  • He often chooses locality of behavior

Example

Example: Consider ChessBoard Class.

class ChessBoard {
	...
	... cout << "Your Move";
};

This is actually somewhat bad design. ChessBoard should not print to the screen.

What if I instead want to print to a file? Cannot use the same class without replacing couts with printing to a file.

class ChessBoard {
	ostream& out;
	istream& in;
	public:
		ChessBoard(ostream& out, istream& in): out{out}, in{in} {}
		...
		...
		out << "Your Move";
};

Little more flexible, but still has issues. What if we want a graphic display? Or to change the language, or to communicate over the internet?

We have low Cohesion, violating SRP. ChessBoard is doing multiple things: manipulate state, implement logic, control rendering to the screen.

Instead: chessBoard should communicate via results, parameters, exceptions. Allow other classes to handle communication with the user.

Should main be performing communication? No - limits reusability.

Possible solution: Use the MVC architecture, well-suited for SRP.

By decoupling presentation, input, and data/logic, we follow SRP, and promote re-use in our programs.

On the other hand, there may be parts of the specifications that are unlikely to change, and so adding layers of abstraction just to follow SRP may not be worthwhile.

Avoiding needless complexity is also worthwhile - use your best judgement.

Next