This website uses cookies to better the user experience of its visitors. Where applicable, this website uses a cookie control system, allowing users to allow or disallow the use of cookies on their computer/device on their first visit to the website. This complies with recent legislative requirements for websites to obtain explicit consent from users before leaving behind or reading files such as cookies on a user’s computer/device. To learn more click Cookie Policy.

Privacy preference center

Cookies are small files saved to a user’s computer/device hard drive that track, save, and store information about the user’s interactions and website use. They allow a website, through its server, to provide users with a tailored experience within the site. Users are advised to take necessary steps within their web browser security settings to block all cookies from this website and its external serving vendors if they wish to deny the use and saving of cookies from this website to their computer’s/device’s hard drive. To learn more click Cookie Policy.

Manage consent preferences

These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
Cookies list
Name _rg_session
Provider rubygarage.org
Retention period 2 days
Type First party
Category Necessary
Description The website session cookie is set by the server to maintain the user's session state across different pages of the website. This cookie is essential for functionalities such as login persistence, ensuring a seamless and consistent user experience. The session cookie does not store personal data and is typically deleted when the browser is closed, enhancing privacy and security.
Name m
Provider m.stripe.com
Retention period 1 year 1 month
Type Third party
Category Necessary
Description The m cookie is set by Stripe and is used to help assess the risk associated with attempted transactions on the website. This cookie plays a critical role in fraud detection by identifying and analyzing patterns of behavior to distinguish between legitimate users and potentially fraudulent activity. It enhances the security of online transactions, ensuring that only authorized payments are processed while minimizing the risk of fraud.
Name __cf_bm
Provider .pipedrive.com
Retention period 1 hour
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to support Cloudflare Bot Management. This cookie helps to identify and filter requests from bots, enhancing the security and performance of the website. By distinguishing between legitimate users and automated traffic, it ensures that the site remains protected from malicious bots and potential attacks. This functionality is crucial for maintaining the integrity and reliability of the site's operations.
Name _GRECAPTCHA
Provider .recaptcha.net
Retention period 6 months
Type Third party
Category Necessary
Description The _GRECAPTCHA cookie is set by Google reCAPTCHA to ensure that interactions with the website are from legitimate human users and not automated bots. This cookie helps protect forms, login pages, and other interactive elements from spam and abuse by analyzing user behavior. It is essential for the proper functioning of reCAPTCHA, providing a critical layer of security to maintain the integrity and reliability of the site's interactive features.
Name __cf_bm
Provider .calendly.com
Retention period 30 minutes
Type Third party
Category Necessary
Description The __cf_bm cookie is set by Cloudflare to distinguish between humans and bots. This cookie is beneficial for the website as it helps in making valid reports on the use of the website. By identifying and managing automated traffic, it ensures that analytics and performance metrics accurately reflect human user interactions, thereby enhancing site security and performance.
Name __cfruid
Provider .calendly.com
Retention period During session
Type Third party
Category Necessary
Description The __cfruid cookie is associated with websites using Cloudflare services. This cookie is used to identify trusted web traffic and enhance security. It helps Cloudflare manage and filter legitimate traffic from potentially harmful requests, thereby protecting the website from malicious activities such as DDoS attacks and ensuring reliable performance for genuine users.
Name OptanonConsent
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonConsent cookie determines whether the visitor has accepted the cookie consent box, ensuring that the consent box will not be presented again upon re-entry to the site. This cookie helps maintain the user's consent preferences and compliance with privacy regulations by storing information about the categories of cookies the user has consented to and preventing unnecessary repetition of consent requests.
Name OptanonAlertBoxClosed
Provider .calendly.com
Retention period 1 year
Type Third party
Category Necessary
Description The OptanonAlertBoxClosed cookie is set after visitors have seen a cookie information notice and, in some cases, only when they actively close the notice. It ensures that the cookie consent message is not shown again to the user, enhancing the user experience by preventing repetitive notifications. This cookie helps manage user preferences and ensures compliance with privacy regulations by recording when the notice has been acknowledged.
Name referrer_user_id
Provider .calendly.com
Retention period 14 days
Type Third party
Category Necessary
Description The referrer_user_id cookie is set by Calendly to support the booking functionality on the website. This cookie helps track the source of referrals to the booking page, enabling Calendly to attribute bookings accurately and enhance the user experience by streamlining the scheduling process. It assists in managing user sessions and preferences during the booking workflow, ensuring efficient and reliable operation.
Name _calendly_session
Provider .calendly.com
Retention period 21 days
Type Third party
Category Necessary
Description The _calendly_session cookie is set by Calendly, a meeting scheduling tool, to enable the meeting scheduler to function within the website. This cookie facilitates the scheduling process by maintaining session information, allowing visitors to book meetings and add events to their calendars seamlessly. It ensures that the scheduling workflow operates smoothly, providing a consistent and reliable user experience.
Name _gat_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _gat_UA-* cookie is a pattern type cookie set by Google Analytics, where the pattern element in the name contains the unique identity number of the Google Analytics account or website it relates to. This cookie is a variation of the _gat cookie and is used to throttle the request rate, limiting the amount of data collected by Google Analytics on high traffic websites. It helps manage the volume of data recorded, ensuring efficient performance and accurate analytics reporting.
Name _ga
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga cookie is set by Google Analytics to calculate visitor, session, and campaign data for the site's analytics reports. It helps track how users interact with the website, providing insights into site usage and performance.
Name _ga_*
Provider rubygarage.org
Retention period 1 year 1 month 4 days
Type First party
Category Analytics
Description The _ga_* cookie is set by Google Analytics to store and count page views on the website. This cookie helps track the number of visits and interactions with the website, providing valuable data for performance and user behavior analysis. It belongs to the analytics category and plays a crucial role in generating detailed usage reports for site optimization.
Name _gid
Provider rubygarage.org
Retention period 1 day
Type First party
Category Analytics
Description The _gid cookie is set by Google Analytics to store information about how visitors use a website and to create an analytics report on the website's performance. This cookie collects data on visitor behavior, including pages visited, duration of the visit, and interactions with the website, helping site owners understand and improve user experience. It is part of the analytics category and typically expires after 24 hours.
Name _dc_gtm_UA-*
Provider rubygarage.org
Retention period 1 minute
Type First party
Category Analytics
Description The _dc_gtm_UA-* cookie is set by Google Analytics to help load the Google Analytics script tag via Google Tag Manager. This cookie facilitates the efficient loading of analytics tools, ensuring that data on user behavior and website performance is accurately collected and reported. It is categorized under analytics and assists in the seamless integration and functioning of Google Analytics on the website.

SOLID Object-Oriented Design Principles with Ruby Examples

  • 75758 views
  • 8 min
  • Mar 15, 2017
Oleg P.

Oleg P.

Ruby/JS Developer

Maryna Z.

Maryna Z.

Copywriter

Share

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!

CONTENTS

Authors:

Oleg P.

Oleg P.

Ruby/JS Developer

Maryna Z.

Maryna Z.

Copywriter

Rate this article!

Nay
So-so
Not bad
Good
Wow
32 rating, average 4.75 out of 5

Share article with

Comments (5)
PRIYANSHU AGARWAL
PRIYANSHU AGARWAL about 7 years ago
Very Nice article... Thanks for making this so explanatory
Reply
Vasya Boychuk over 6 years ago
In part about LSP: you fixed return format of posts method, but changed behaviour by added filter by `post.popular?`
Reply
Maryna Z.
Maryna Z. over 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.
Reply
Karan
Karan about 5 years ago
Very clear explanation with ruby code examples! Thanks for the article :)
Reply
Anastasia Z.
Anastasia Z. about 5 years ago Karan
Hi! We're glad you enjoy our work. Keep up with our blog updates for more useful information ;)
Reply

Subscribe via email and know it all first!