http://www.perlmonks.org?node_id=854066

perlpal has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perl Monks ,

Is it in conformance with Perl standards to implement a module as a class which exports variables/functions at the same time ?

In continuity , is there a norm to decide when to implement Perl modules as classes and when to implement them as traditional modules ?

Thanks in advance

Replies are listed 'Best First'.
Re: Heterogenous perl modules
by kennethk (Abbot) on Aug 10, 2010 at 15:20 UTC
    "Perl standards" is a bit of an oxymoron - methods/structures/formats/paradigms used depend very much on for/with whom you are working. But, if we appeal to Perl Best Practices (as transcribed on the Perl Best Practices Reference Guide), we find the following relevant points:

    192. Make object orientation a choice, not a default.
    193. Choose object orientation using appropriate criteria.
    223. Export judiciously and, where possible, only by request.

    From this, I conclude "it depends". Why do you think it's necessary to have an object class that exports methods? Why do you think it's a good idea to be using objects in your context? Are you taking about exporting by default or just exposing the methods for import (@EXPORT_OK)? If the export question is just about including class/static methods, you can do this simply using package methods (Foo::Bar->method()). If the subroutines you intend to export are general utilities, it likely makes sense to put them in a second, traditional module. You can do what you want (that's some of what makes Perl great), but standards are about code maintenance - will what you do today be obvious to someone else in 6 months time? Mixing paradigms is a good way to move that closer to "no".

Re: Heterogenous perl modules
by TGI (Parson) on Aug 11, 2010 at 06:02 UTC

    You can do pretty much what you want. I have made simple modules that provided both object methods and exported functions. But I try to avoid such mixing. This practice can easily add to confusion, especially in complex systems.

    I prefer to keep my OOP modules separate from my traditional, exporting modules.

    If I do have a group of functions that are useful in relation to a class hierarchy, I include them in one or more collections of related utility functions. In other words, the entire module is written for normal procedural use. I also prefer to keep utility functions that are for use by the class hierarchy separate from those intended for use by consumers of the class hierarchy.

    My rules of thumb for using OOP are pretty simple. If I have a group of routines that work with a data structure more than 3 levels deep, I always break it up into objects. If I have a group of functions that take the same arguments, I'll probably make an object or objects that encompasses them.


    TGI says moo