Send Messages, Don't rely on manipulating data – Part 2 (OOP)

_config.yml

I’m reading Sandi Metz’s book POODR.

I would like to focus specifically on some things which I thought required more detail in the book: that of hiding data strictures.

In the last post we talked about how when we want to make a change, we want to make it in only one place. And from that one place, we want everything to be taken care of and just work. What we don’t want to do is create a situation where we have to change 300 things, by making one simple change. Or even worse would be to try to make one change - and to then find yourself making 100 other changes in many different places. This post is an extension of the that principle. We only want to make changes once.

Consider this situation: [45, 150] You have an array of numbers. The first number reflects a person’s age. The second number reflects a person’s weight. So 45 years old and a weight of 150 would be how you interpret that particular array.

Now consider the scenario which is inevitable. The boss walks in and says: “You know there’s a change coming in. We’re getting all our data in hashes. You’ll have to change the person class to reflect this.”

You roll your eyes. OMG. Another change. Why can’t they just leave me alone or make up their minds? First it’s an array, now a hash, tomorrow it will be something else!

So you refill your coffee and begin the aruduous task of changing everything.

That’s six changes. What a pain.

But is there a better way?

Let’s wind back the clock.

Let’s write the code so that the data structure is hidden. All we need to do now is to ask for a person’s age. .e.g. betty = Person.new([85, 130]).age and you get the answer that you are looking for: 85. Why would you want to query for the person’s age when you have already passed it into the object’s “constructor”? That’s a separate matter.

Now when the boss demands you to change your code to a hash. All you need to do is to make the change in a few places (as opposed to six).

The basic point is to have the data structure hidden behind your classes. Send messages wherever possible.

Hope you learned something. And I hope this helps.

Written on April 14, 2017