Design Patterns in Ruby
I have recently been wearing the Software Architect hat more often and so decided to pick up my trusted Design Patterns in Ruby book. I reread it and these are my takeaways:
- In your code, seperate out the things that change from those that stay the same. This is the ground rule when using patterns and will get you closer to an Ideal System, where all changes are local. How? Make the parts in your system as loosely coupled as you can. This means programming to an Interface, not an Implementation. This is actually not so different from what Heroku calls Explicit Contracts.
- Assemble behaviors in modules, and use composition over inheritance.
- Use delegate more often.
Page 15 of the book lists the 14 patterns and gives a concise overview of when to use which pattern.
Here are my personal "definitions" to help me remember the patterns:
- Template Method: Vary one step.
- Strategy: Vary the whole algorithm. When there are multiple ways to do something and you want to choose at runtime. aka: interchangeable parts
- Adapter: Layer a new interface over an object to make the interface compatible. eg: SmtpAdapter and SmsAdapter.
- Observers: Decouple! Listen to what happens in another class.
- Decorators: Classes that support the same basic interface, making them all chainable. aka: alias_method_chain & extend. see ActiveSupport.
- Proxies: Good for controlling the interface to another object. eg: security, network performance, caching
- Facade: Kind of a proxy that wraps a simple interface over a complex interface.
All Ruby programmers should read Design Patterns in Ruby before they start building software with some level of complexity. Also, everybody who wants to understand why Rails is built like it is, or wants to extend/contribute to Rails, read this book!