Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 134 ยท Object-Oriented Ruby

Design Principles in Ruby

Apply SOLID, small objects, composition over inheritance, dependency injection and the null object pattern in idiomatic Ruby, with runnable before-and-after examples.

Ruby lets you write almost anything, so the language will not stop you from building a 600-line class that does everything. Design principles are the habits that keep programs easy to change: small objects with clear jobs, collaborators that can be swapped, and as little knowledge as possible shared between parts. They were mostly named in statically typed languages, but Ruby's flexibility (duck typing, blocks, modules) makes several of them much lighter to apply.

This lesson walks through the SOLID principles in Ruby terms, then three practical techniques you will use constantly: composition over inheritance, dependency injection, and the null object pattern. Every principle is shown as a "before" that hurts and an "after" that works. It builds on Duck Typing and Polymorphism, Inheritance and Modules and Mixins.

Principles are guides, not laws. Use them when a design starts to hurt (code that is hard to test, change or understand), not as a checklist for every ten-line script.

Single Responsibility: one reason to change

A class should have one job, which means one reason to change. The warning sign is a class whose description needs the word "and": "it calculates the total and formats the receipt and saves it".

Ruby Splitting a class with three jobs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Invoice knows about money, InvoicePrinter knows about text layout, and InvoiceArchive knows about storage. Changing the receipt format touches only the printer, and you can test the total without any printing code.

Open/Closed: extend without editing

Code should be open for extension but closed for modification: adding a new case should not mean editing a case statement in five places. In Ruby the usual tool is polymorphism through duck typing: give each variant an object that answers the same message.

Ruby Replacing a growing case with objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

checkout never changes when a new discount arrives; BlackFriday was added without touching existing code. A lambda also satisfies this: ->(price) { price - 10 } with call instead of apply is often even lighter, see Procs and Lambdas.

Liskov Substitution: subtypes must keep promises

Anywhere your code expects a parent class, a subclass must work without surprises. Ruby will not enforce this, so you must. The classic violation is a subclass that refuses what its parent allows.

Ruby A subclass that breaks its parent's promise (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The loop prints Sparrow flies and then dies with main.rb:8:in 'Penguin#fly': penguins cannot fly (NotImplementedError). Any code that handles birds in general now has to special-case penguins. The fix is in the model, not in a clever rescue: a Penguin is a Bird, but flying is not something all birds do, so model it separately.

Ruby Fixing the hierarchy by modelling the ability

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A useful test for any inheritance relationship: could every caller that uses the parent also use the child, without checking its type? If not, reach for composition or a module instead.

Interface Segregation: ask only for what you need

Do not force a collaborator to provide methods it does not use. In Ruby there is no interface keyword; the "interface" is just the set of methods a function calls. Keep that set small. A report writer that only needs each can accept any enumerable, not just an Array:

Ruby Depending on a small interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

print_numbered asks for each_with_index, which any Enumerable has, so arrays, ranges and your own Inbox all work. If it demanded an Array, Inbox could not be used.

Dependency Inversion and injection

High-level code should not construct its low-level collaborators; it should receive them. In Ruby this is as simple as passing an object into initialize. This is called dependency injection, and it needs no framework.

Here is the "before": a class that creates its own clock and mailer, which makes it impossible to test without real time and real email.

Ruby Injecting collaborators through the constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because the clock and the mailer are parameters, the test controls both: the "current" day is always 14, and no real email goes anywhere. Default values (clock: -> { Time.now }) keep production callers simple. Any object with a deliver(to, text) method works as a mailer, a perfect use of duck typing. More on this in Test Doubles.

Composition over inheritance

Inheritance says "is a"; composition says "has a". Inheritance couples a subclass to every detail of its parent and cannot be changed at runtime. Composition builds behavior by combining small objects, and you can swap parts freely.

Ruby Composition instead of a subclass explosion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

With inheritance you would need classes like ShoutingTrimmingFormatter for every combination. Here three tiny parts combine into any pipeline, including a lambda, because each part just responds to call.

A good rule: use inheritance for a true, stable "is a" relationship where the parent defines a template; use a module for shared behavior; use composition for everything that can vary.

The Null Object pattern

Many NoMethodError: undefined method for nil crashes come from code that returns nil to mean "nothing here" and callers who forget to check. A null object is a real object that implements the same interface and does nothing harmful.

Ruby nil crashes, then a null object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first attempt prints crash: undefined method 'label' for nil. After reopening User so that plan falls back to NoPlan, callers never check for nil again. Use this where a missing value has a sensible default behavior (guest user, empty logger, free plan); do not use it to hide real errors, and prefer &. (see Ternary, Safe Navigation and Short-Circuit) for one-off cases.

Other habits that scale

  • Tell, don't ask: order.mark_paid beats reaching into order.payment.status = :paid. Objects should do their own work.
  • Law of Demeter: talk to your direct collaborators, not to their collaborators' collaborators. A chain like a.b.c.d is a smell.
  • Small methods and classes: if you cannot name a method in a few words, it is doing too much.
  • Prefer plain data for plain data: Struct and Data (Struct and Data) avoid writing boilerplate classes.
  • Delay abstractions: wait for the second or third example before extracting an interface, so you abstract what really varies.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which sentence best signals that a class violates the Single Responsibility Principle?

    SRP is about reasons to change. A class that does several unrelated jobs changes for several unrelated reasons.
  2. 2. A Penguin subclass of Bird raises NotImplementedError in fly. Which principle does this break?

    Code that works with any Bird fails when given a Penguin, so the subclass cannot substitute for its parent.
  3. 3. What is dependency injection in Ruby?

    It is just passing the collaborator in (usually through initialize), which makes it replaceable in tests.
  4. 4. Why is composition often preferred to inheritance?

    Inheritance ties a class to its parent's details forever. Composed parts can be mixed and replaced independently.
  5. 5. What does a null object give its callers?

    A null object stands in for 'nothing' while still answering the same messages, so callers need no nil checks.

Summary

  • Give each class one reason to change (Single Responsibility), and add behavior by adding objects, not by editing a growing case (Open/Closed).
  • Subclasses must work wherever the parent is expected (Liskov); model abilities with modules when they do not.
  • Depend on small interfaces such as each or call (Interface Segregation), and pass collaborators in rather than building them (dependency injection).
  • Prefer composition over inheritance for anything that can vary.
  • Use a null object to replace nil where "nothing" has a harmless default behavior.
  • Apply principles when the design hurts, not as ceremony.

Next: Design Patterns