SOLID & Ruby in 5 short examples

Tech - RubyCademy
RubyCademy
2 min readDec 7, 2018

--

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

Introduction

SOLID is an acronym that stands for a set of principles to help developers to produce long-term maintainable source code that uses 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.

If a change occurs on the way to log — for example, logging in a file instead of a simple one puts — then only the Logger class must be impacted as it’s the only class that is responsible for 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 modify it directly

Here, the Array class remains unchanged when the Collection class — as a specialization 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 behavior of the RoleLogger#print_role method.

Interface Segregation principle

The Interface Segregation Principle (1996)

Dependency Inversion principle

The Dependency Inversion Principle (1996)

To go further

You can follow us on Twitter as we’re very active on this platform.

Indeed, we post elaborate code examples every day.

Also, I created RubyCademy Weekly which is a weekly newsletter.

Uncover crucial knowledge I wish I had when starting my career as a Rails developer!

This newsletter provides valuable Ruby tips, essential concepts, and patterns.

I deep dive into ADVANCED TOPICS with multiple CASE STUDIES!

Join us and get access to our exclusive content!

>>> RubyCademy Weekly <<<

💚

--

--