Part I: Patterns and Ruby
Chapter 1: Building Better Programs with Patterns
The first few times we see a problem we may improvise and invent a solution on the spot, but if that same problem keeps reappearing, we will come up with a standard operating procedure to cover it. Don’t, as the old saying goes, keep reinventing the wheel.
In 1995, Enrich Gamma, Richard Helm, Ralph Johnson, and John Vlissides set out to redirect all the effort going into building redundant software wheels into something more useful. They published Design Patterns: Elements of Reusable Object-Oriented Software . Those four were known as the Gang of Four (GoF).
The GoF identified 23 patterns with a focus on some key questions: How do objects like the ones you tend to find in most systems relate to one another? How should they be coupled together? What should they know about each other? How can we swap out parts that are likely to change frequently?
Four points the GoF book ideas boil down to:
- Separate out the things that change from those that stay the same.
- Program to an interface, not an implementation.
- Prefer composition over inheritance.
- Delegate, delegate, delegate.
Say we want to create a class for cars and a method of driving:
my_car = Car.new my_car.drive(200)
and then we wanted to add airplane as well:
if is_car my_car = Car.new my_car.drive(200) else my_plane = AirPlane.new my_plane.fly(200) end
The problem here is that we focused on the implementation, not the interface.
From the interface point of view, we will consider just one class that would be helpful when we ever think of adding trains, or any other vehicle. Something like:
my_vehicle = get_vehicle my_vehicle.travel(200)
- The YAGNI ( You Ain’t Gonna Need It ) principle simply says that you should not implement features or design in flexibility, that you don’t need right now . Why? Because chances are, you ain’t gonna need it later , either.
Design patterns are all about making your systems more flexible, more able to roll smoothly with change.
- 14 out of GoF’s 23 design patterns are discussed in this book:
- Template Method
- Strategy object
- Observer pattern
- Composite pattern
- Iterator pattern
- Command pattern
- Decorator pattern
- Factory Method
- Abstract Factory
- Builder pattern
In this chapter, the author justifies why learning design patterns is important for building better software programs. Although this book in Ruby language, the author makes it easy for beginners in the language. Stay tuned because if you are a Ruby beginner, the next chapter will come to your rescue.
See you in chapter 2 notes!
Get Design Patterns in Ruby from Amazon!!
Image by the Author