Date: May 30, 2009
-
Design is all about dependencies
- If you refer to something, you depend on it.
- When the things you depend on change, you must change.
-
Resistance is a resource => Listen to what the pain is telling you. Listen to what the code smells are telling you. Embrace the friction. Fix the problem.
-
On assessing the design:
- When you get to the refactor stage of red-green-refactor, ask yourself ...
- Is it DRY?
- Does it have one responsibility?
- Does everything change at the same rate?
- Does it depend on things that change less than it does?
- When the answer to all of these things is 'yes', the design is probably in good shape.
- When you get to the refactor stage of red-green-refactor, ask yourself ...
-
"Triangle of Responsibility" Refactoring
- Refactor
- Extract - Pull functionality out where necessary
- Inject - Inject that new dependency into place from which it was extracted
-
What if I don't know where I want this refactoring to take me?
- That's OK. In fact, that's typical.
- "Refactor, not because you know the abstraction, but because you want to find it."
- "You don't have to know where you're going to successfully refactor."
- When you see someone's code and think it's beautiful and you wonder how they thought of it, they didn't. They evolved it to that point.
-
When injecting dependencies into a class, do so only via arguments to the #initialize method
def intialize(downloader=FTPDownloader.new) @downloader = downloader end
-
When you need to inject a few dependencies, you can use an options hash to remove the dependency on the order of the arguments
def intialize(opts) @env = opts[:env] || Rails.env filename = opts[:filename] end
-
How to assess: "Does each object depend on things that change less than it does?"
- Line up the objects from left to right
- Left = lower likelihood of change
- Right = higher likelihood of change
- Only depend on things on your left
- Line up the objects from left to right
-
Recommended reading
- Design Principles and Design Patterns paper by Robert Martin
- Growing Object-Oriented Software Guided by Tests by Steve Freeman and Nat Pryce