|No such thing as a small change|
Re: OOP's setter/getter method - is there a way to avoid them?by BrowserUk (Patriarch)
|on Oct 28, 2015 at 08:57 UTC||Need Help??|
My question is, are setters and getters still used these days in Perl programming?
I've followed the responses to this thread with interest. The sum total of them seems to be: getters and setters are okay because they are internal to the class.
I say, for the most part, that is phooey.
Well written classes for most objects should never need setters and getters for their internal attributes.
An example: A BankAccount class.
One way to write that it to have a getter and a setter for the balance attribute. The code charged with processing transactions receives a transaction for a particular account number; creates an instance (proxy) for that account; calls the $act->get_balance() method to retrieve the current balance; adds or subtracts the transaction amount depending if it is a deposit or withdrawal; then calls the $act->set_balance() method to store the revised amount. This is WRONG!
The transaction processing code should: instantiate the account, and the pass the transaction object to $act->transact( $trans ) method. That method then performs all the required checks and balances before finally -- assuming all is well -- modifying the balance attribute to reflect the transaction.
Well designed classes should (almost) never need to expose their internal attributes to the outside world via setters & getters. Calling code should not query current values, modify them and then set them back; it should pass the information detailing the change to an appropriate method that will perform that task.
That's why I'll never be a Mo(o)(u)(se) user. Pretty much the only thing those modules do for you is automate the construction of setters and getters along with validating the values passed to them. But as (almost) no class should ever require getters & setters that is all redundant.
As for validation: If all values entering the class come in via 'do something useful' methods, by the time the objects attributes get around to being modified, the logic of those methods has already ensured that the values being set into attributes are valid; so further indirection and validation is both redundant and noxious.
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
In the absence of evidence, opinion is indistinguishable from prejudice.