This post is a response to chapter 2 of Sandi Metz’s Practical Object-Oriented Design in Ruby (POODR). I applied the teachings from this chapter to transform data (instance variables) into behavior (methods). The result is a class that is easier to change, and class objects that are easier to read and write.
In the example below, I created a simple Artist class, which demonstrates the magic of using attr_accessor. attr_accessor transforms instance variables into reader & writer methods that you can use to get or set data to each instance/object of your class. For the longhand version of attr_accessor, see lines 14-22 below. attr_accessor obviates the need for writing these methods out. However, it is important to grasp their syntax.
The beauty of transforming data into methods is that you don’t have to use instance variables (@name, @song) throughout your code. More important, by replacing instance variables with their attr_accessor methods, you are able to change a name or song on a whim without changing your code. Metz summarizes this trick: “Implementing this method changes [name] from data (which is referenced all over) to behavior (which is defined once).”