in reply to Re: Re^5: OO Getters/Setters
in thread OO Getters/Setters
From my point of view, there are very few times when you would want to expose member variables (a.k.a attributes) to the public
But if you're blindly adding accessors/mutators, you might has well have made them public. This isn't a blanket ban on accessors/mutators, but a note that people should be more careful about adding them.
You spoke of tied scalars etc, but by that argument you invalidated your previous argument over performance.
Perl's objects are already slow. In any case, my tied scalar example was nothing more than an example. It demonstrates that $obj->attr and $obj->{attr} are only different in syntax, since you could use a tied scalar to preform exactly the same operations that an accessor/mutator could do. I don't recommend either approach, though, but rather eliminating accessors/mutators all together whenever possible.
Which of these is a better object for a vending machine?
sub money . . . # Accessor/mutator to how much money is in the machine sub get_drink . . . # Spit a drink out
Or this, which avoids mutators entirely:
sub insert_coin . . . # Insert a coin (quarter, dime, whatever) into m +achine sub money . . . # Accessor to how much money is in the machine sub get_drink . . . # Spit a drink out
The second one will restrict what kind of money you can put it and adds that coin's value to the internal attribute. It is not a mutator, because it doesn't provide direct access to that attribute. money is an accesor in either case, but I don't consider it a problem, since the user needs some way of figuring out how much money is in the machine so they can insert more if need be. get_drink has the same implementation in either case, and would only spit a drink out if there was enough money in the machine.
The second interface is more complex, but it's a better design because we've abstracted the operation of inserting coins into the machine. We can subclass it to take other kinds of coins or to take cash (though insert_coin wouldn't be the best name in that case). The point is that you've restricted what kind of data can go in, which the first class would have a much harder time doing.
----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer
: () { :|:& };:
Note: All code is untested, unless otherwise stated
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Re^5: OO Getters/Setters
by linux454 (Pilgrim) on Jan 02, 2004 at 20:00 UTC | |
by hardburn (Abbot) on Jan 02, 2004 at 20:29 UTC | |
by linux454 (Pilgrim) on Jan 02, 2004 at 21:12 UTC | |
by hardburn (Abbot) on Jan 02, 2004 at 21:47 UTC |