Learning objectives:
- Discuss each principle and its benefits
Structure:
- Discuss each principle in theory and by looking at examples
- Further resources
SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable.
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.
SOLID helps us write code that is:
- Loosely coupled: dependency injection
- Highly cohesive: single responsibility
- Easily composable: can be changed
- Content independent: can be rearranged
- Reusable
- Easily testable
- Easy to maintain and extend over time
A class should have a single responsibility
There should never be more than one reason for a class to change
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' 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 are developing an application's logic.
SRP code reveal intent and generates high cohesive code.
class FinancialReportMailer
def initialize(transactions, account)
@transactions = transactions
@account = account
@report = ""
end
def generate_report!
@report = @transactions.map {
|t| "amount: #{t.amount} type: #{t.type} date: #{t.created_at}"
}.join("\n")
end
def send_report
Mailer.deliver(
from: 'reporter@example.com',
to: @account.email,
subject: 'your report',
body: @report
)
end
end
mailer = FinancialReportMailer.new(transactions, account)
mailer.generate_report!
mailer.send_reportInstead:
class FinancialReportMailer
default from: "reporter@example.com"
def send_report(report, account)
@report = report
@account = account
mail(
to: @account.email,
subject: "Financial report",
body: @report,
)
end
end
class FinancialReportGenerator
attr_reader :transactions
def initialize(transactions)
@transactions = transactions
end
def generate
transactions.map do |t|
"amount: #{t.amount} type: #{t.type} date: #{t.created_at}"
end.join("\n")
end
end
report = FinancialReportGenerator.new(transactions).generate
FinancialReportMailer.send_report(report, account).deliverAfter 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.
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 behaviour 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.
In the code below, the Logger class formats and sends logs. But the OCP principle isn't followed, since we will have to modify the logger every time we need to add additional senders or formatters:
class Logger
def initialize(format, delivery)
@format = format
@delivery = delivery
end
def log(string)
deliver format(string)
end
private
def format(string)
case @format
when :raw
string
when :with_date
"#{Time.now} #{string}"
when :with_date_and_details
"Log was creates at #{Time.now}, please check details #{string}"
else
raise NotImplementedError
end
end
def deliver(text)
case @delivery
when :by_email
LogMailer.send_report(
from: "emergency@example.com",
to: "admin@example.com",
subject: "Logger report",
body: text,
)
when :by_sms
client = Twilio::REST::Client.new("TWILIO_SID", "TWILIO_AUTH_TOKEN")
client.account.messages.create(
from: "SOME_NUMBER",
to: "ANOTHER_NUMBER",
body: text,
)
when :to_stdout
STDOUT.write(text)
else
raise NotImplementedError
end
end
end
logger = Logger.new(:raw, :by_sms)
logger.log("Emergency error! Please fix me!")In the example below, we have segregated senders and formatters to separate classes, and enabled the addition of new senders and formatters without having to modify the base code:
class Logger
def initialize(formatter: DateDetailsFormatter.new, sender: LogWriter.new)
@formatter = formatter
@sender = sender
end
def log(string)
@sender.deliver @formatter.format(string)
end
end
class LogSms
FROM = "SOME_NUMBER"
attr_reader :to
def initialize(to = "ANOTHER_NUMBER")
@to = to
end
def deliver(text)
client.account.messages.create(from: FROM, to: to, body: text)
end
private
def client
@client ||= Twilio::REST::Client.new(ENV("TWILIO_SID"), ENV("TWILIO_AUTH_TOKEN"))
end
end
class LogMailer
default from: "emergency@example.com"
def deliver(text)
mail(
to: "admin@example.com",
subject: "Logger report",
body: text,
)
end
end
class LogWriter
def deliver(log)
STDOUT.write(text)
end
end
class DateFormatter
def format(string)
"#{Time.now} #{string}"
end
end
class DateDetailsFormatter
def format(string)
"Log was creates at #{Time.now}, please check details #{string}"
end
end
class RawFormatter
def format(string)
string
end
end
logger = Logger.new(formatter: RawFormatter.new, sender: LogSms.new)
logger.log("Emergency error! Please fix me!")Subclasses should add to a base class' 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 organise class hierarchies.
In the example below, 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.
class UserPosts
def initialize(user)
@user = user
end
def posts
@user.blog.posts
end
end
class PopularPosts < UserPosts
def posts
user_posts = super
user_posts.map do |post|
if post.popular?
"title: #{post.title} author: #{post.author}"
end
end.join("\n")
end
endInstead:
class UserPosts
def initialize(user)
@user = user
end
def posts
@user.blog.posts
end
end
class PopularPosts < UserPosts
def posts
user_posts = super
user_posts.select { |post| post.popular? }
end
def formatted_posts
posts.map { |post| "title: #{post.title} author: #{post.author}" }.join("\n")
end
endTo 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.
Clients shouldn't depend on methods they don't use. Several client-specific interfaces are better than one generalised 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:
class CoffeeMachineInterface
def select_drink_type; end
def select_portion; end
def select_sugar_amount; end
def brew_coffee; end
def clean_coffee_machine; end
def fill_coffee_beans; end
def fill_water_supply; end
def fill_sugar_supply; end
end
class Person
def initialize
@coffee_machine = CoffeeMachineInterface.new
end
def make_coffee
@coffee_machine.select_drink_type
@coffee_machine.select_portion
@coffee_machine.select_sugar_amount
@coffee_machine.brew_coffee
end
end
class Staff
def initialize
@coffee_machine = CoffeeMachineInterface.new
end
def service
@coffee_machine.clean_coffee_machine
@coffee_machine.fill_coffee_beans
@coffee_machine.fill_water_supply
@coffee_machine.fill_sugar_supply
end
endIn the example above, we have a piece of code that represents a coffee vending machine interface. As we can see, the interface is used by two types of users: a Person and a Staff. However, each uses only a few interface abilities. The ISP principle tells that one class should contain only the methods it uses.
To make this example comply with the ISP principle, we create two interfaces: a separate user interface and a separate staff interface. With this design segregated in two interfaces, we avoid unused methods and now have two smaller interfaces with methods that perform specific tasks:
class CoffeeMachineUserInterface
def select_drink_type; end
def select_portion; end
def select_sugar_amount; end
def brew_coffee; end
end
class CoffeeMachineServiceInterface
def clean_coffee_machine; end
def fill_coffee_beans; end
def fill_water_supply; end
def fill_sugar_supply; end
end
class Person
def initialize
@coffee_machine = CoffeeMachineUserInterface.new
end
def make_coffee
@coffee_machine.select_drink_type
@coffee_machine.select_portion
@coffee_machine.select_sugar_amount
@coffee_machine.brew_coffee
end
end
class Staff
def initialize
@coffee_machine = CoffeeMachineServiceInterface.new
end
def service
@coffee_machine.clean_coffee_machine
@coffee_machine.fill_coffee_beans
@coffee_machine.fill_water_supply
@coffee_machine.fill_sugar_supply
end
endImage credit: https://levelup.gitconnected.com/interface-segregation-principle-made-simple-990da495441c
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
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.
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.
class Printer
attr_reader :data
def initialize(data)
@data = data
end
def print_pdf
PdfFormatter.new.format(data)
end
def print_html
HtmlFormatter.new.format(data)
end
end
class PdfFormatter
def format(data)
# format data to Pdf logic
end
end
class HtmlFormatter
def format(data)
# format data to Html logic
end
endInstead:
class Printer
attr_reader :data
def initialize(data)
@data = data
end
def print(formatter: PdfFormatter.new)
formatter.format(data)
end
end
class PdfFormatter
def format(data)
# format data to Pdf logic
end
end
class HtmlFormatter
def format(data)
# format data to Html logic
end
endIn the code above, the printer 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 are able to easily change the low-level logic without system-wide implications.
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 are 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.
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.
Credit: the above was adjusted from SOLID Object-Oriented Design Principles with Ruby Examples
- SOLID object-oriented design by Sandi Metz, GORUCO 2009 (video, 47:12 watch) or on vimeo
- SOLID Ruby by Jim Weirich, Ruby Conf 2009 (video, 46:18 watch)
- Less, the path to better design, by Sandi Metz, GORUCO 2011 (video, 41:04 watch)
- SOLID Principles in Ruby (article, 6 mins read)





