SOLID Object-Oriented Design Principles with Ruby Examples

  • 8 min
  • Mar 15, 2017
Oleg P.

Oleg P.

Ruby/JS Developer

Maryna Z.

Maryna Z.



Clean code is not written by following a set of rules. You don’t become a software craftsman by learning a list of heuristics. Professionalism and craftsmanship come from values that drive disciplines.
Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Robert C. Martin, or Uncle Bob ‒ co-author of the Agile Manifesto ‒ introduced his set of SOLID principles for object-oriented design way back in 1995. These practical recommendations help developers design flexible solutions, detect code smells, and refactor their code to prevent the issues. By following SOLID design principles, developers can achieve a maintainable and extendable codebase.

In this article, we’ll talk a bit about practical uses of SOLID principles rather than focusing on theory, and will demonstrate common violations of SOLID principles in Ruby, the programming language we work closely with at RubyGarage.

For starters, let’s explain what SOLID stands for:

SOLID Principles Acronym

Now let’s take a closer look at each of these SOLID principles.

Single Responsibility Principle

The Single Responsibility Principle (SRP) is the following: “A class should have a single responsibility.” In other words, any complicated classes should be divided into smaller classes that are each responsible for a particular behaviour, making it easier to understand and maintain your codebase.

While the concept behind the SRP is quite clear, however, developers admit that putting this principle into practice requires some skill, since a class’s responsibility isn’t always immediately clear.

Martin considers responsibility as a reason to change and concludes that a class and a module should have the only reason to be changed. Combining two entities that change for different reasons at different times is bad design. Leaving each class with a single responsibility makes classes maintainable. The goal of the SRP principle is to fight complexity that creeps in while you’re developing an application’s logic.

Now let’s take a look at an example of code that doesn’t follow the single responsibility principle:

The class FinancialReportMailer shown above handles two tasks: report generation (method “generate_report!”) and report sending (method “send_report”). The class looks quite simple as written. However, expanding this class in the future may be problematic, since we’ll likely have to change the logic of the class. The SRP principle tells us that a class should implement one single task, and therefore according to this principle we should divide the FinancialReportMailer class into two classes.

Let’s see what this code looks like after we’ve refactored it to comply with the SRP:

After refactoring, we have two classes that each perform a specific task. The FinancialReportMailer class sends emails containing texts generated by the FinancialReportGenerator class. If we wanted to expand the class responsible for report generation in the future, we could simply make the necessary changes without having to touch the FinancialReportMailer class.

Open-Closed Principle

The Open-Closed Principle (OCP) states that “Modules, classes, methods and other application entities should be open for extension but closed for modification.” Put simply, all modules, classes, methods, etc. should be designed in a modular way so that you (or other developers) are able to change the behavior of the system without changing the source code.

This principle is important to follow because the codebase of software projects is often modified throughout their lifetimes ‒ for example, to meet new customer requirements. Therefore, a developer’s goal should be to build a flexible system that is easy to modify and extend. The open–closed principle helps developers achieve a flexible system architecture.

Before we view an example of code that complies with the OCP principle, we’ll take a look at some code that demonstrates a violation of OCP. In the code below, the Logger class formats and sends logs. But the OCP principle isn’t followed, since we’ll have to modify the logger every time we need to add additional senders or formatters:

After we refactor this code, it will be able to be extended. In the example below, we’ve segregated senders and formatters to separate classes and enabled the addition of new senders and formatters without having to modify the base code:

Liskov Substitution Principle

Many developers find the Liskov Substitution Principle (LSP) tangled and complicated. This is how Robert Martin defines the LSP principle: “Subclasses should add to a base class’s behaviour, not replace it.” In a more informal interpretation, the principle states that parent instances should be replaceable with one of their child instances without creating any unexpected or incorrect behaviour. Therefore, LSP ensures that abstractions are correct, and helps developers achieve more reusable code and better organize class hierarchies.

Now that we know what the LSP principle is getting at, let’s consider a piece of code that violates LSP. In the example below, we are implementing user statistics. There are two classes: a base class (UserStatistic) and its child class (AdminStatistic). The child class violates the LSP principle since it completely redefines the base class by returning a string with filtered data, whereas the base class returns an array of posts.

Now let’s see how we refactored the code so it conforms to the Liskov substitution principle:

To comply with the LSP principle, we can segregate the filtration logic and the statistics string generation logic into two methods: “posts“ and “formatted_posts“. Therefore, we refactored the method posts that filtrates user posts, so the method returns the same type of data as the base class.

The Interface Segregation Principle

The Interface Segregation Principle (ISP) can be described as follows: “Clients shouldn’t depend on methods they don’t use. Several client-specific interfaces are better than one generalized interface.”

Simply put, main classes should be segregated into smaller specific classes, so their clients use only methods they need. As a result, we get the interfaces segregated according to their purpose, so we avoid “fat” classes and code that’s hard to maintain. The ISP principle is best demonstrated with the piece of code. This is how looks the code that is crammed with generic functionality:

In the example above, we have a piece of code that represents a coffee vending machine interface. As you can see, the interface is used by two types of users: a Person and a Staff. Each uses only a few interface abilities, however. For example, the class Person uses only the following methods: “select_drink_type“, “select_portion“, “select_sugar_amount“, and “brew_coffee“. The ISP principle tells that one class should contain only the method it uses.

To make this example comply with the ISP principle, we created two interfaces: a separate user interface and a separate staff interface. In the “CoffeeMachineUserInterface,” a user will be able to choose a drink type (method “select_drink_type“), choose a portion size (method “select_portion“), select the amount of sugar they would like added to the drink (method “select_sugar_amount“), and start brewing the coffee (method “brew_coffee“). A staff member, using the “CoffeeMachineSeviceInterface,” will be able to choose among the following operations: clean the machine (method “clean_coffee_machine“), fill sugar (method “fill_sugar_supply“), fill coffee beans (method “fill_coffee_beans“), and fill water supply (method “fill_water_supply“).

With this design segregated in two interfaces, we’ve avoided unused methods and now have two smaller interfaces with methods that perform specific tasks:

The Dependency Inversion Principle

The Dependency Inversion Principle (DIP) suggests that “High-level modules shouldn’t depend on low-level modules. Both modules should depend on abstractions. In addition, abstractions shouldn’t depend on details. Details depend on abstractions.”

Interestingly, Martin doesn’t consider the DIP principle to be a completely separate principle, but claims that the DIP principle is simply the result of strictly following two other SOLID principles: Liskov substitution and open-closed. According to Martin, code that follows the LSP and OCP principles should be readable and contain clearly separated abstractions. It should also be extendable, and child classes should be easily replaceable by other instances of a base class without breaking the system.

In the code below, we have implemented logic for a printer (the Printer class has the method print which performs data output).

The class Printer depends on classes PdfFormatter and HtmlFormatter instead of abstractions, which indicates the violation of the DIP principle since the classes PdfFormatter and HtmlFormatter may contain the logic that refers to other classes. Thus, we may impact all the related classes when modifying the class Printer:

Let’s see an example of code that conforms to the DIP principle. Implementation of low-level details (outputting formats like PDF and HTML) is done in separate classes (PDF Formatter and HTML Formatter):

In the code above, the printer ‒ a high-level object ‒ doesn’t depend directly on the implementation of low-level objects ‒ the PDF and HTML formatters. In addition, all modules depend on abstraction. Our high-level functionality is separated from all low-level details, so we’re able to easily change the low-level logic without system-wide implications.

In conclusion, remember that SOLID principles themselves don’t guarantee great object-oriented design. Apply SOLID principles smartly. To do so, you need to know exactly what problem you’re trying to solve and if the problem is truly a risk for your system. For example, excessively segregating classes to conform with the SRP principle may lead to low cohesion and even performance losses.

Simply checking off boxes and saying “Now my code conforms to SOLID design principles” is the wrong approach. Remember the quote at the beginning of this article, reminding us that clean code can’t be written just by following a set of rules.

However, if applied correctly, SOLID design recommendations can help you build system architecture that is easy to modify and extend over time, which is precisely what every developer should strive for. RubyGarage team is always open to collaboration, so if you want to get a code review or recommendations on how to improve your code quality, feel free to get in touch!



Oleg P.

Oleg P.

Ruby/JS Developer

Maryna Z.

Maryna Z.


Rate this article!

Not bad
32 rating, average 4.75 out of 5

Share article with

Comments (5)
PRIYANSHU AGARWAL over 6 years ago
Very Nice article... Thanks for making this so explanatory
Vasya Boychuk about 6 years ago
In part about LSP: you fixed return format of posts method, but changed behaviour by added filter by `post.popular?`
Maryna Z.
Maryna Z. about 6 years ago
Hi! In the second piece of code that illustrates the LSP principle, we've fixed our mistake by adding the required logic with the same type of output data as in the parent class. Such logic doesn't violate the LSP principle. Actually, that's what we need to redefine methods for: in order to change the logic according to our requirements.
Karan over 4 years ago
Very clear explanation with ruby code examples! Thanks for the article :)
Anastasia Z.
Anastasia Z. over 4 years ago Karan
Hi! We're glad you enjoy our work. Keep up with our blog updates for more useful information ;)

Subscribe via email and know it all first!