DEV Community

Cover image for Revisiting The S in SOLID
Elyess Eleuch
Elyess Eleuch

Posted on

Revisiting The S in SOLID

to start with, this is how I understood it. If you want to add something to it, feel free to contact me. I would be happy :).

WHAT IS SOLID?

Single Responsibility (S)
Open/Closed (O)
Liskov Substitution (L)
Interface Segregation (I)
Dependency inversion (D)

SOLID principles were first defined by Robert C. Martin in his book Design Principles and Design Patterns. Then the acronym SOLID was introduced by Michael Feathers.

Martin’s and Feathers’ design principles encourage us to create more maintainable, understandable, and flexible software.
But today we will be talking about the Single Responsibility Principle.

The problem that they address :

The main problem that they tackle is working with legacy code.
But wait for a second, what is the problem with legacy code?

Here you go :

  1. Re-reading code multiple times to get the part you need to change
  2. Hard to understand what a method does *(Big giant methods that do everything ) *(or weird old names that do not refer to the logic of the method anymore)

With the legacy code, we spend more time reading than writing code

Simply:

It is most of the time bad code. And what leads to that?

The strategy that many of the startups adapt:

  1. Constantly adding new features
  2. No formal process
  3. No time to worry about code structure ( daily releases, very dynamic)

And like uncle Bob says: Bad code slows us down, we want to be quick right, but not quick in a sloppy way.

A developer should behave like a surgeon, steady, confident but have the deadline in mind.

Single Responsibility Principle:

“A class should have one, and only one reason to change”

In other words, don’t put functions that change for different reasons in the same class.

We want to create small classes with very specific names that are responsible for only one thing.

Example: We have a car that has model, speed and interior components as properties.

Our class would look like this:
Car Class

And let’s suppose we want to print out the properties:
Output Class

Notice here we don’t want to declare the printer methods inside the car class, but that would violate our principle.

The Car class shouldn’t change because we want to output the text to some domain.com but only because the properties of the car changed.

Benefits: Easier Testing, fewer dependencies

Sources :

Meyer, B. (1997): Object-Oriented Software Construction, 2nd edition
http://www.cvc.uab.es/shared/teach/a21291/temes/object_oriented_design/materials_adicionals/principles_and_patterns.pdf
Robert C. Martin “Principles of OOD”
https://www.youtube.com/watch?v=zHiWqnTWsn4&t=2707s
https://www.youtube.com/watch?v=rtmFCcjEgEw
https://www.baeldung.com/solid-principles

Top comments (0)