sub name { my $self = shift; return $self->{name}; }
This seems wrong to me. If you have a method whose sole purpose is to retrieve a property, you have bad OO design, either on the part of the language or the class. My guess is, both. (Hopefully, Perl6 will fix the language part.)
Let me talk about the language first. It shouldn't be necessary to write a method just for that; it should be possible to just expose the property directly, and later if it needs to have more complex behavior added, transform it into a method without the need to change any external code that uses it. Inform programmers do this sort of thing with their objects all the time -- take a description property that was a string formerly and, to give it more complex behavior, turn it into a routine. External code does not need to know or care that the description is now a routine instead of a simple string; the result, from the perspective of something outside the object, is the same. Thus, above, the name property shouldn't need an accessor method; the scalar property should just be exposed directly; only if more complex behavior is needed should it be turned into a method. I believe the only reason you would ever write an accessor method is because the language lacks any way for external code to call a property without caring whether it's a scalar or a routine that returns a scalar.
Now, if the language doesn't provide these facilities, then I can understand the temptation to make everything go through an accessor method, so that everything does not have to change if complex behavior is later added that makes the method necessary. Still, I think the added baroqueness of code created by having a lot of methods that don't actually do anything except set or return a value is in many cases more trouble than it's worth. I've been known to do it, and I don't know that it's inherently wrong per se, but I have some strong reservations about making claims to the effect that things should *always* be done this way; it sounds like something a misguided C++ programmer would say, who doesn't know any better because he hasn't learned any other paradigms yet. I believe there may be cases where it's cleaner to expose the scalar properties directly, if it can be determined that they're definitely going to remain as simple scalars in future versions of the class. This can make for simpler code in some cases, and simpler code is easier to maintain, all else being equal.
$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/
In reply to Re: Make your classes use their own methods
by jonadab
in thread Make your classes use their own methods
by petdance
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |