http://qs321.pair.com?node_id=286624

This meditation arises from an afternoon when I discovered how bad I coded a module; I put it here as an amonishment of a bad practice that I, and others hopefully, will definitely avoid in the future.

A couple of days ago, I was playing with a module of mine that I dared to put on the CPAN. The module seemed to work so well in all previous tests I made that I was planning to put out a 1.00 version and to work on a 2.00 release that would use delegation instead of inheritance.

At a certain moment, I saw something in my application that wasn't working as expected... for some reason, an array had one more element added on its tail without any direct intervention. After peeking around the values into the array in different points of the program I concluded that the array was altered inside the module and not by the application.

What happened was that on object creation I passed a reference to the array as a parameter.

Unfortunately, the code of my module looks like this:

. . . sub new { my $class = shift ; my %args = @_ ; . . . my %localparms ; @localparms{@myParmNames} = delete @args{@myParmNames} ; . . . while (my ($parm,$value) = each %localparms) { $ldap->{"net_ldap_express_$parm"} = $value ; } return $ldap ;

As you can see, the reference you pass to the new method goes directly into the object. Therefore, if you alter the array in your program it will be altered for the object, too; vice-versa, if the object alters the array, your application data will be garbled

A safer implementation would, first of all, use accessors to set the values in the object; in turn, the accessors would copy the values inside the object instead of putting them directly into it.

Happy coding!
--bronto

Update (after diotalevi's reply): If I pass, say, an array reference to an object, and the object alters the referenced array, I don't like it, but I still can stand it (once I know that the object will do that, of course ;-). What I find definitely a bad thing is the opposite effect: you change something in the program, and that alters the internal state of an object... isn't it a violation of encapsulation? And in OOP, isn't that a bad thing?


The very nature of Perl to be like natural language--inconsistant and full of dwim and special cases--makes it impossible to know it all without simply memorizing the documentation (which is not complete or totally correct anyway).
--John M. Dlugosz