SRP
Single Responsibility Principle
Replay "POODR" book
by Sandi Metz
Thomas Petrachi
Twitter: @thmszpy
Youtube: http://www.youtube.com/channel/thomasPetrachi
Vodeclic: www.vodeclic.com
Blog: blog.space-a.fr
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
Example
Bicycles + gears
Example
The "Gear" class
Example
Adding more logic
Example
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:
- Mr Gear, what is your ratio?
- Seems fine
- Mr Gear, what is your tire?
- Seems ridiculous
Single Responsibility
When to change
"What is the future cost of doing nothing today?"
Coding Techniques
A few guidelines:
- Hide instance variables
- Hide data structures
- Extract responsibilities (from methods)
- Isolate responsibilities
Hide Instance Variables
Always use accessors
Then you can override if nexessary
Hide Data Structures
Each method has knowledge of the @data structureEach 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
becomes
Avoids the need for comments and improves reusability
Isolate Responsibilities
#diameter method doesn't belong in Gear class
Conclusion
SRP allows you to:
-
Anticipate future changes (like a real Wheel class)
- Change without consequence
- Reuse without duplication
Thanks !
Any questions?
SRP
By Thomas Petrachi
SRP
- 2,562