Isolating Extra Responsibilities
September 16, 2013
Today I got a chance to read through Chapter 2 of Practical Object-Oriented Design in Ruby which is about designing classes with a single responsibility.
In this chapter we start by building a simple class with single responsibility, but then we start adding to it and it quickly starts to do more than one thing. The problem that we face as our class starts to grow is that we still aren’t clear about the future responsibilities of our program and so we aren’t quite ready to build a completely new class yet to separate our responsibilites. One thing you can do as you start to break apart you growing class is to create a Struct. Creating a struct might only be a temporary solution, but it allows us to clean up our class and defer any future decisions about building a second class.
Here is an example of creating a struct:
Rectangle = Struct.new(:length, :width) do
def area
length * width
end
end
Here is some more info on structs from Steve Klabnik that you might find useful.