in reply to Tied Variables - why?
I think you've stumbled onto one of the reasons why people use tied variables in the first place in your second example :
the output you'll get here (unless the Squareable author's been exceptionally concerned about creating a default accessor) is something similar to "Squareable=HASH(address)", not 25. print $var would print 25, however, when set up as a tied scalar.# objects my $var = new Squareable(5); $var->square(); print $var; # oh... yields 25... neato!
Tied variables are set up to provide the programmer with a simple way of using accessors and mutators without having to worry about semantics at all.
I'd use create a tieable class if I were concerned about making a class behave and operate "just like" one of perl's 3 variable types.
When used correctly, tied variables can reduce the amount of knowledge a programmer needs to have about a given class ("Is squarable's output method ->output(), or ->product(), or ->result() ?" vs. "print $foo"). There's an excellent example in Damian Conway's OOP book that uses math classes : It's not as clear to have
as it would be to have$int->add(4); $int->divide(12); print $i->value();
(I can't remember offhand if tied variables allow you to use += and friends right now, or if that's just overloading, so I'll play it basic...)$i=$i+4; $i=$i/12; print $i;
As with anything, if tied variables are not a common part of your toolbox, comment their uses through your code to remind you and your maintainers of what's going on.
|
|---|