Single Responsibility Principle

Replay "POODR" book 
by Sandi Metz

Thomas Petrachi

Twitter: @thmszpy


O.O. Design

Easy-to-change application

  • No unexpected side effects
  • Easy to reuse
  • Small product changes == small code changes

Single responsibility

Deciding what belongs in a class


Bicycles + gears


The "Gear" class


Adding more logic


The "Gear" class

Single Responsibility

Is this the best way to organize code?

Single Responsibility

Why does SRP matters?

Without SRP:
  • Difficult to reuse
  • Leads to code duplication
  • Or to useless dependencies

Single Responsibility

Determining SRP:
  1. Mr Gear, what is your ratio?
  2. Seems fine

  1. Mr Gear, what is your tire?
  2. Seems ridiculous

Single Responsibility

When to change

"What is the future cost of doing nothing today?"

Coding Techniques

A few guidelines:
  1. Hide instance variables
  2. Hide data structures
  3. Extract responsibilities (from methods)
  4. Isolate responsibilities

Hide Instance Variables

Always use accessors
Then you can override if nexessary

Hide Data Structures

Each method has knowledge of the @data structure

Each method will need to change if @data changes

Hide Data Structures

Encapsulate knowledge of @data structure
Only #weelify method will change if @data changes

Extract Responsibilities

Two responsibilities in one method
Avoids the need for comments and improves reusability

Isolate Responsibilities

#diameter method doesn't belong in Gear class


SRP allows you to:
  • Anticipate future changes (like a real Wheel class)
  • Change without consequence
  • Reuse without duplication

Thanks !

Any questions?