http://qs1969.pair.com?node_id=1146899


in reply to Re: Behavior of 'our' variables in the package-namespace
in thread Behavior of 'our' variables in the package-namespace

Notice how the inclusion of an initialise() function gets rid of the BEGIN block, useful in avoiding paying the piper if you don't actually create any objects of this class for whatever reason

I like the potential flexibility there, although I'll also (for the sake of other readers and devil's advocacy) point out that if a caller wanted to put off overhead of loading a module, it's best done in a require() call in whatever conditional requires that module.

Simply calling require() causes Perl to do extra work (searching the @INC path for a matching module, reading it in, and so on) can be overhead a consuming codebase can avoid if it's well-written. Of course, if the design requires it know in advance the support is there, or the program cannot function without the library, it's best to take the performance hit upfront.

Not to say efficiency is a bad thing, but I also try to avoid premature optimization, or saving a library/package consumer from their own bad design ;). Where I really like your suggestion is when a package has the potential to do some relatively expensive setup that's only required in certain cases. Maybe a huge amount of data needs to be parsed to do a particular task, yet callers might just want to do a more trivial task that the package supports. Here I think your point about delaying such expensive initialization could have great benefits.


Also notice that the use of an accessor shifts all of the code for that accessor to one clearly defined location, ...

Yup, I appreciate the reminder, but the proof-of-concept was intentionally terse to limit the scope. I'm definitely an advocate of accessors, ideally with similar (or at least well-documented) syntax/design to the methods used to set those same object settings/values.


I also like using named parameters for the constructor, even when only passing one or two parameters. It makes inheritance and future expansion of the class a lot simpler.

That's a good point. I've often stuck with a single value when I had no intention of expanding a constructor, but that breaks down when the design does change in the future; being friendly to subclassing, possibly by other authors, is a great reason to consider named key/value hashes even in the simple case.