SOLID & Ruby in 5 short examples

In this article we’re going to explore the following topics:

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle


SOLID is an acronym that stands for a set of principles to help developers to produce long-term maintainable source code that use an object oriented programming language.

DISCLAIMER: as it’s just a set of principles, obviously it won’t replace your common sense.

This said, let’s detail each principle with a simple and short example.

PS: Due to duck typing design, Interface Segregation and Dependency Inversion principle are not relevant in Ruby.
Otherwise, I provide interesting resources in both sections about these principles for the most curious developers.

Single Responsibility principle

This principle is based on the fact that a class should be responsible of only one aspect of a program. By responsible we mean that the class can be impacted by a change in only one aspect of the program.

Of a change occurs on the way to log — for example, logging in a file instead of a simple puts— then only the Logger class must be impacted as it’s the only class that is responsible of logging.

Open/Closed principle

This principle is based on the fact that a class should be open for extension and closed for modification.

This means that is preferable to derivate from the class that you want to use than modifying it directly

Here, the Array class remains unchanged when the Collection class — as a specialisation of Array — still gets the properties of an array.

So this pattern, allows you to add a set of functionalities and modify Array’s existing methods without impacting all the other instances of Array.

Liskov Substitution principle

This principle is based on the fact that a derived class must be substitutable by its base class

In this example, the RoleLogger#print_role method takes a role argument.

In our case the Admin and User classes derivate from Role.

We can easily interchange these classes without breaking the expected behaviour of the RoleLogger#print_role method.

Interface Segregation principle

The Interface Segregation Principle (1996)

Dependency Inversion principle

The Dependency Inversion Principle (1996)


May I have your attention please 🎤🎤

Feel free to subscribe here:

Thank you for taking the time to read this post :-)

Feel free to 👏 and share this article if it has been useful for you. 🚀

Here is a link to my last article: Modules in Ruby: Part I