# Sunday, 15 February 2009

Well perhaps not all the way to Considered Harmful but Allen Holub is willing to call them Evil. I came across this article because I'm teaching OO Analysis and Design again this year and my students have generally already heard that the way you do encapsulation is you make all your attributes private and then add a public get and set method for every attribute. What's more, they generally feel if you change the type of the attribute then you need to change the return type of the get and the parameter type of the set. This of course gets you pretty much nowhere, and this is what Allen is railing against.

Now I am OK with Get methods as long as you swear you will never change the return type. The example I give the students is a bank account class with a balance. In the original design you keep the balance as a floating point number, 12.34000000 for 12 dollars and 34 cents. You add a GetBalance() method that returns a float, and Deposit() and Withdraw() methods that take (among other things) floats to represent the amount being deposited or withdrawn. Now when implementation time rolls along you discover that floating point arithmetic is expensive computationally, and needs lots of rounding to stay accurate: add 1.00 to 1.00, then add another 1.00 and the time may come when your number ends .01 or .99 ... neither of which banks care for tremendously. So you decide to store the balance as an integer number of pennies. Everything is OK in my book as long as you DO NOT CHANGE the signature of GetBalance(), nor of Deposit and Withdraw. These methods don't need to know what you just did. When Deposit tells you the amount is 50.00 dollars, your code can multiply by 100 to get 5,000 pennies, and add that to the balance. GetBalance() can divide by 100 (and round) to change pennies to dollars. That's a good use of a Getter method.

I am less OK with Set methods. I sure don't want a SetBalance() method. Deposit(), Withdraw(), and their cousins will change the balance. But there's no business rule in which it becomes necessary to announce that account 123456 now has $183.27 in it, and set the balance to that number. Having the method just encourages some code outside the class to do things that belong in the class - calculating service charges, or giving interest perhaps. Locking up access to the value means that if your business rules change, you don't need to look outside the bank account class for code that implements those business rules.

So do I think Get and Set methods are Evil? No, but I do think they should not be your first reflex, one of each per attribute. Make them earn their place.


Sunday, 15 February 2009 16:47:44 (Eastern Standard Time, UTC-05:00)  #    Comments [0]