![]() |
|
Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
Re: Using constant to override (abstract) methods.by ELISHEVA (Prior) |
on Mar 28, 2011 at 09:39 UTC ( #895873=note: print w/replies, xml ) | Need Help?? |
The more important issue to me is why? Although your approach 'works', I should think the use of constant to define overrides would be very confusing to future maintainers. For one, not everyone knows that constants are actually subs. Your coworker's confusion and many posts here I think testify to that. (look on Super Search). Second, use constant is not the obvious place to look for a method that overrides a superclass method. Third, it is somewhat misleading. The word "constant" implies immutable. That might lead someone to think that you have defined a final method. Perhaps that is even your reason for wanting to use "constant" this way? However, methods defined via use constant are not final. They can be overridden by any subclass because they are, after all subs. For example,
Performance wouldn't be a reason to use constants in this way either. Perl optimizes constant methods even when they are not explicitly defined as constants. According to Constant Functions: Functions with a prototype of () are potential candidates for inlining. If the result after optimization and constant folding is either a constant or a lexically-scoped scalar which has no other references, then it will be used in place of function calls made without & . There is nothing special about use constant. You can see the source code for the use constant pragma here. It is just Perl code that converts use constant X => Y into sub X() { Y }. If anything, you are adding overhead to your startup code as compared with a simple sub definition since the pragma has to analyze each X => Y and generate the necessary symbols. Update: added comments about performance.
In Section
Seekers of Perl Wisdom
|
|