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

_config.yml

I’m reading Sandi Metz’s book POODR. If only she added more examples. I thought to document my ideas where there are shortfalls. Hopefully you’ll learn something too.

Take the example bellow. Freddie has an account with the Dawes, Tomes, Mousely, Grubbs Fidelity Fiduciary Bank. Here are the details of his activities:

Everything is going smooth. Until something changes. Code would be a lot easier to maintain if there were not these damn changes ruining our lives! (Of course, we must manage change effectively). Now the UK government has made a law that every time you access money from your bank account then the government will automatically credit to you 25% of your account balance! This is better than passing Go and collecting $200. The problem is that we’d have to change the code in multiple places:

Now that’s a real pain in the butt. What if we make a mistake and forget to change something? Wouldn’t it be nice if we only had to change it in one place?

See the code below:

Compare the above code with the first two examples. What is the difference between them? In the above code, the change is only made once, and it is propagated throughout. It’s much easier to maintain and make changes which apply everywhere. It brings up an important point: NEVER access your internal class fields without getting them through a common access point – either via a property (as above), or via a “getter” or “setter” method. In other words, never code like in the first two examples. You must only code like in the third example. It will save you much grief. I hope you learned something!

Written on April 13, 2017