Syntactic Confectionery Delight | |
PerlMonks |
Refactoring Perl #7 - Remove Assignments to Parametersby agianni (Hermit) |
on Aug 23, 2007 at 04:01 UTC ( [id://634565]=perlmeditation: print w/replies, xml ) | Need Help?? |
Initially this may strike you as a simple refactoring pattern and the mechanics of it are. Here's how it looks in Perl:
becomes:
Fowler's primary reason for promoting this pattern is to address the "lack of clarity and to [sic] confusion between pass by value and pass by reference". (p. 131) Note: my original writeup contained a number of factual errors, which I believe I have corrected. This is important in Java for reasons that Fowler explains, but I don't care to pretend I know or understand Java enough to elaborate. In Perl everything is passed by reference. Updating a parameter passed as a reference -- i.e. modifying $_[$x] or a copy of a reference contained therein -- could have unexpected consequences and is best avoided. Thanks to ikegami for pointing out that Perl is always pass by reference, contrary to my original suggestion to the contrary. The exception would be in the situation where a subroutine would otherwise modify and return a very large data structure or object or where you will call a subroutine many, many times to modify and return any data passed to it. In these situations, it may be appropriate to pass in a reference, modify it within the subroutine and not return it. This is not a pre-optimization that I would recommend, as I think it makes code less maintainable, but it is an optimization to be considered if you find your code to be slow. I should point out that this is much less likely to be a problem in Perl than in other programming languages, but there are situations where it is an appropriate technique.
Back to
Meditations
|
|