Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??

Writing a rock-solid general-purpose CPAN module is hard. Very hard. After all, such modules are expected to work flawlessly in a wide variety of environments -- many of which the author may have no experience in.

To illustrate how hard it can be to write a module that works in many different environments, consider two recent examples. Schwern gushes here about the joy he derives from coaxing his lovingly crafted Test::More module to work faultlessly in multi-threaded environments -- even though he never uses threads himself. And in CHECK and INIT under mod_perl, Ovid reminds us that writing a CPAN module that works smoothly in a mod_perl environment is not trivial.

To help those CPAN authors less experienced than an Ovid or a Schwern, I've tried to provide some tips and links on improving CPAN module quality.

Choosing a Module Name

The Pause Module List gives some excellent advice which I won't repeat here. I will offer a word of warning, however: if you trample on the global namespace, you will be flamed! Two recent attacks that spring to mind are: Unix-0.02 where the name Unix was chosen not because the module had anything to do with Unix, but because it was "Unix inspired" (fanning the flames, the author then published a rebuttal of the criticisms in his module's POD ... which led to more flames for perverted use of POD); and Util where the author, in a desperate attempt to flee the relentless cpanrating flames, moved his module from the global to the Acme namespace (though clearly it does not belong in either). So, save yourself a lot of pain and discuss your module name in a public forum (typically the module-authors@perl.org mailing list) well before you upload it to the CPAN. If you are introducing a new module in an area where others exist, please take the time to clearly describe how your module differs from them and why you wrote it.

The most relevant piece of naming advice from Perl Best Practices is practice 3.1: "Use grammatical templates when forming identifiers". For packages and classes, a suitable template is:

Abstract_noun Abstract_noun::Adjective Abstract_noun::Adjective1::Adjective2
For example:
package Disk; package Disk::Audio; package Disk::DVD; package Disk::DVD::Rewritable

Module Reviews

If you're lucky, your module might be reviewed at cpan ratings or gav's CPAN wiki or Mark Fowler's lovely Advent Calendar or Neil Bowers CPAN Module Reviews (2012 update) or even here in the Perl Monks Module Reviews section. You might even try posting a request for review at Simon's code review ladder. Update Oct 2011: A new PrePAN module review site is now up. However, you're unlikely to gain much from these sources simply because performing a detailed, quality module review is very time consuming and few people have the time and inclination to do it.

A more practical alternative is to isolate small pieces of code from the module that you're unhappy with and post multiple small questions to Perl Monks. Much more likely to elicit a response than posting a 1000-line module for review.

Another approach is to review your own module, using the checklists below. When reviewing your own module, it's helpful to perform several reviews, each one from a different perspective: beginner user perspective, expert user perspective, maintenance programmer perspective, support analyst perspective, and so on. Many programmers (including me) don't pay enough attention to the customer view of the system. I've found the simple act of pretending to be a first time user or a support phone jockey uncovers many ideas for improving quality.

Module Review Checklist

I'll start by listing the general areas that a module review might cover; those areas that I have an interest in, I'll discuss in a bit more detail later.

  • Module interface and ease-of-use. See perlmodstyle and On Interfaces and APIs.
  • Testability and Test Suite (see next section).
  • Documentation. Tutorial and Reference. Examples and Cookbook. Maintainer doco. Document how your module is different to similar ones. Change log. Notes re portability, performance, bugs, limits, caveats, bug reporting, ...
  • Stylistic issues: consistency, variable naming, indentation, magic numbers, commenting, long subs, global variables, ...
  • Review the module with regard to the 256 guidelines in Perl Best Practices.
  • Use a tool to test kwalitee (e.g. Perl::Critic, Module::CPANTS, Devel::Cover, Devel::SawAmpersand, Perl::MinimumVersion, Devel::Cycle, Test::Memory::Cycle, lint, valgrind, ...).
  • Use common and well-known idioms and programming practices.
  • Sniff out code smells.
  • Portability.
  • Performance.
  • Robustness (see Solidity checklists below).
  • Security. See Security techniques every programmer should know, How to answer "Perl is not secure" objections? and pjf's excellent perl security course notes, Perl Training Australia's Security notes released.
  • Error Handling. Document all errors in the user's dialect. Prefer throwing exceptions to returning special values.
  • Are edge cases handled properly?
  • Plays well with others. Don't use $&, $', $`, don't export anything by default, localize Perl globals, Makefile.PL evilness (e.g. phone home).
  • Avoid code and other duplication.
  • Simplicity and Clarity.
  • Generality and Extensibility.
  • Abstraction and Encapsulation.
  • Reuse and Decoupling.
  • Maintainability.
  • Supportability and Traceability.

See also On Coding Standards and Code Reviews.

Testability and Test Suite

Was the test suite written before, during or after the module? The benefits of Test Driven Development are well known and I won't further elaborate here.

Are there nicely commented tests covering the examples in the documentation? I strongly encourage this because: it acts as tutorial material for someone browsing the test suite; and it ensures the examples given in the documentation actually work.

How isolated/independent are the tests? Can they be run in any order? Are boundary conditions tested? Are errors and exceptions tested?

How maintainable is the test suite? How long does it take to run? Is it one monolithic script or broken into a number of smaller ones, one per functional area? Are Mocks/Stubs employed, where practicable, to test platform-specific features on all platforms?

Test suite code coverage (via Devel::Cover) should be at least 80% in my view. POD coverage should be 100% and is easily enforced via pod-coverage.t (auto-generated by Module::Starter):

use Test::More; eval "use Test::Pod::Coverage 0.08"; plan skip_all => "Test::Pod::Coverage 0.08 required for testing POD co +verage" if $@; all_pod_coverage_ok();

Update (2009): Nowadays, you can use Test::XT to generate "best practice" author tests. See also this alias use.perl.org journal.

General Code Solidity Checklist

Programming languages, such as C++ and Java, tend to classify routines as:

  • unsafe (uses unprotected global or static state)
  • thread-safe (aka MT-safe)
  • async-signal-safe (reentrant)
  • exception-safe

(There is also async-cancel-safe, which is of little practical importance). Update: As pointed out by BrowserUk below, the above categories, though important when writing C extensions, are mostly irrelevant at the Perl level. I'd be interested if anyone could provide examples of where the above categories are relevant when writing pure Perl code.

Thread Safety

Update: please see BrowserUk's response below for thread safety advice at the Perl level.

It's not easy to determine if a piece of code is thread safe. Nor is it easy to write tests to prove its thread safety. However, armed with an understanding of thread safety, a careful examination of the code will prove fruitful. Note that thread safety and reentrancy (aka efficient thread safety) should be considered early (at the C level) since they often affect interfaces and are hard to retrofit later.

See perlthrtut for information on Perl thread safety. An interesting twist in making a Perl module thread-safe is working around core constructs and modules known to be thread-unsafe. For instance, Test::More v0.51_01 was changed to use a Perl sort block rather than a subroutine because sort subroutines are known to be thread-hostile (perl bug #30333 discussed in Perl threads sort test program crashes).

Exception Safety

In C++, the dominant exception handling idiom is RAII (Resource Acquisition is Initialization), which I much prefer to the Java Dispose pattern. Though RAII can't be used in full garbage collected languages, such as Java and Perl 6, it can work well in simple reference counted languages, like Perl 5.

To give a very simple example, this code:

sub fred { open(FH, "< f.tmp") or die "open error f.tmp"; # ... process file here die "oops"; # if something went wrong close(FH); } eval { fred() }; if ($@) { print "died: $@\n" } # oops, handle FH is still open if exception was thrown.
is not exception-safe because FH is not closed when die is called. A simple remedy is to replace the global FH with a lexical file handle (which is auto-closed at end of scope (RAII)):
sub fred { open(my $fh, "< f.tmp") or die "open error f.tmp"; # ... process file here die "oops"; # if something went wrong close($fh); } eval { fred() }; if ($@) { print "died: $@\n" } # ok, $fh is auto-closed when its ref count goes to zero
If you are stuck with Perl 5.005 and can't use a lexical file handle, IO::File or localizing FH with local *FH should do the trick.

See also Best Practices for Exception Handling and Re: Intelligent Exception Handling in Perl and mod_perl exception handling techniques.

Perl-specific Code Solidity Checklist

I've taken the liberty of extending the General Code Solidity Checklist above with some Perl-specific ones:

Sorry, I couldn't resist the last two. ;-) As you can see, there are many things to consider when writing solid Perl code!

Ideally, you should test your taint-safe code both with and without taint because taint mode has been an historical source of bugs and strange differences in behaviour. And you can do that easily enough via the Test::Harness prove command's -T switch. However, if you specify #!/usr/bin/perl -wT in a test script, make test will run it in taint mode only (anyone know of an easy way around this?).

For information on mod_perl safety, see mod_perl reference and chapter 6 (Coding with mod_perl in Mind) of Practical mod_perl (which is now available online).

See Also

Related CPAN Modules

Considered: rinceWind "Edit: promote to tutorials"
Unconsidered: castaway Keep/Edit/Delete: 12/41/0 - We let the author decide if a node is a tutorial.

Updated June 2006: Added more recent references (e.g. PBP) and tools (e.g. Perl::Critic). Jan 2008: Added module naming advice from PBP. Aug 2009: Added new "Related CPAN Modules" section. Oct 2011: Added link to PrePAN. Nov 2012: Added link to Neil Bowers CPAN module reviews.


In reply to Writing Solid CPAN Modules by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others meditating upon the Monastery: (7)
    As of 2014-10-21 04:24 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      For retirement, I am banking on:










      Results (95 votes), past polls