DRYing System Knowledge
Hide Instance Variables Always wrap instance variables in accessor methods instead of referring to variables.[¹]
Hide data from yourself. Doing so protects the code from being affected by unexpected changes.
In Ruby, send messages to access variables, even if you think of them as data. Data very often have behavior that you don’t yet know about.
The references are leaky. They escape encapsulation and insinuate themselves throughout the code.
When you have data in an array, it’s not long before you have references to the array’s structure.[¹]
They are not DRY[²]. The knowledge about the positions of items in an array should not be duplicated. It should be known in one place.
Separate Structure from Meaning
As you can use a method to wrap an instance variable, you can use the Ruby Struct class to wrap a structure.
The official Ruby documentation (http://ruby-doc.org/core/classes/Struct.html) defines Struct as “a convenient way to bundle many attributes together, using accessor methods, without having to write an explicit class.
–
[¹]: Sandi Metz (2013): Practical Object-Oriented Design in Ruby (https://www.amazon.com/Practical-Object-Oriented-Design-Agile-Primer/dp/0134456475)
[²]: Don’t Repeat Yourself https://en.wikipedia.org/wiki/Don%27t_repeat_yourself