Goodbye Getters and Setters or OOP Done Right

They lack behaviour, the break encapsulation — they might as well be C structs.Putting the behaviour where the data is might not seem like a very clear instruction at first glance, but it really is simply a matter of moving the behaviour (computation) into the class where the data required for the calculation is actually held (in order words, putting the behaviour where it really belongs).How do we apply this adage to the problem at hand?Lets look at what the code is actually doing (which really isn’t very clear is it?)On line 9, we’re checking whether our account has sufficient balance to topup the card..Lets give Account a method called hasSuffcientBalanceOf($money)..On lines 10–12 we’re crediting our Card with that amount of $money..Lets give the Card a method called creditWith($money)..On line 13 we’re debiting our Account with that same amount..Lets give it a method called debit($money).Wow!.Look what happened to our CardCharger class:Suddenly it becomes clear what this code actually does!And what’s become of the Card and Account classes?.Lo and behold, not only have they shed their getters and setters, they have become much, much simpler:And of course we can go even further by applying the same logic to the Money class (and of course it too loses its getters):So, you see, putting the behaviour where the data is goes a long way to not only simplify and remove unnecessary code but preserves encapsulation in the way that nature intended!Now , it’s true that sometime you do want (or even need) getters..But in 90% of the cases you most certainly don’t..And what’s more, putting some effort into moving the behaviour where it belongs (with its data) can simplify the code a great deal.In part II of this article I will address how we apply this thinking to some slightly thornier problems using a trick called double-dispatch, which helps to both decoupling, preserving encapsulation and keeping behaviour where it belongs.. More details

Leave a Reply