3 perlmodstyle - Perl module style guide
7 This document attempts to describe the Perl Community's "best practice"
8 for writing Perl modules. It extends the recommendations found in
9 L<perlstyle> , which should be considered required reading
10 before reading this document.
12 While this document is intended to be useful to all module authors, it is
13 particularly aimed at authors who wish to publish their modules on CPAN.
15 The focus is on elements of style which are visible to the users of a
16 module, rather than those parts which are only seen by the module's
17 developers. However, many of the guidelines presented in this document
18 can be extrapolated and applied successfully to a module's internals.
20 This document differs from L<perlnewmod> in that it is a style guide
21 rather than a tutorial on creating CPAN modules. It provides a
22 checklist against which modules can be compared to determine whether
23 they conform to best practice, without necessarily describing in detail
26 All the advice contained in this document has been gleaned from
27 extensive conversations with experienced CPAN authors and users. Every
28 piece of advice given here is the result of previous mistakes. This
29 information is here to help you avoid the same mistakes and the extra
30 work that would inevitably be required to fix them.
32 The first section of this document provides an itemized checklist;
33 subsequent sections provide a more detailed discussion of the items on
34 the list. The final section, "Common Pitfalls", describes some of the
35 most popular mistakes made by CPAN authors.
37 =head1 QUICK CHECKLIST
39 For more detail on each item in this checklist, see below.
41 =head2 Before you start
47 Don't re-invent the wheel
51 Patch, extend or subclass an existing module where possible
55 Do one thing and do it well
59 Choose an appropriate name
69 API should be understandable by the average programmer
73 Simple methods for simple tasks
77 Separate functionality from output
81 Consistent naming of subroutines or methods
85 Use named parameters (a hash or hashref) when there are more than two
96 Ensure your module works under C<use strict> and C<-w>
100 Stable modules should maintain backwards compatibility
110 Write documentation in POD
114 Document purpose, scope and target applications
118 Document each publically accessible method or subroutine, including params and return values
122 Give examples of use in your documentation
126 Provide a README file and perhaps also release notes, changelog, etc
130 Provide links to further information (URL, email)
134 =head2 Release considerations
140 Specify pre-requisites in Makefile.PL
144 Specify Perl version requirements with C<use>
148 Include tests with your module
152 Choose a sensible and consistent version numbering scheme (X.YY is the common Perl module numbering scheme)
156 Increment the version number for every change, no matter how small
160 Package the module using "make dist"
164 Choose an appropriate license (GPL/Artistic is a good default)
168 =head1 BEFORE YOU START WRITING A MODULE
170 Try not to launch headlong into developing your module without spending
171 some time thinking first. A little forethought may save you a vast
172 amount of effort later on.
174 =head2 Has it been done before?
176 You may not even need to write the module. Check whether it's already
177 been done in Perl, and avoid re-inventing the wheel unless you have a
180 If an existing module B<almost> does what you want, consider writing a
181 patch, writing a subclass, or otherwise extending the existing module
182 rather than rewriting it.
184 =head2 Do one thing and do it well
186 At the risk of stating the obvious, modules are intended to be modular.
187 A Perl developer should be able to use modules to put together the
188 building blocks of their application. However, it's important that the
189 blocks are the right shape, and that the developer shouldn't have to use
190 a big block when all they need is a small one.
192 Your module should have a clearly defined scope which is no longer than
193 a single sentence. Can your module be broken down into a family of
198 "FooBar.pm provides an implementation of the FOO protocol and the
199 related BAR standard."
203 "Foo.pm provides an implementation of the FOO protocol. Bar.pm
204 implements the related BAR protocol."
206 This means that if a developer only needs a module for the BAR standard,
207 they should not be forced to install libraries for FOO as well.
209 =head2 What's in a name?
211 Make sure you choose an appropriate name for your module early on. This
212 will help people find and remember your module, and make programming
213 with your module more intuitive.
215 When naming your module, consider the following:
221 Be descriptive (i.e. accurately describes the purpose of the module).
225 Be consistent with existing modules.
229 Reflect the functionality of the module, not the implementation.
233 Avoid starting a new top-level hierarchy, especially if a suitable
234 hierarchy already exists under which you could place your module.
238 You should contact modules@perl.org to ask them about your module name
239 before publishing your module. You should also try to ask people who
240 are already familiar with the module's application domain and the CPAN
241 naming system. Authors of similar modules, or modules with similar
242 names, may be a good place to start.
244 =head1 DESIGNING AND WRITING YOUR MODULE
246 Considerations for module design and coding:
248 =head2 To OO or not to OO?
250 Your module may be object oriented (OO) or not, or it may have both kinds
251 of interfaces available. There are pros and cons of each technique, which
252 should be considered when you design your API.
254 According to Damian Conway, you should consider using OO:
260 When the system is large or likely to become so
264 When the data is aggregated in obvious structures that will become objects
268 When the types of data form a natural hierarchy that can make use of inheritance
272 When operations on data vary according to data type (making
273 polymorphic invocation of methods feasible)
277 When it is likely that new data types may be later introduced
278 into the system, and will need to be handled by existing code
282 When interactions between data are best represented by
287 When the implementation of system components is likely to
288 change over time (and hence should be encapsulated)
292 When the system design is itself object-oriented
296 When large amounts of client code will use the software (and
297 should be insulated from changes in its implementation)
301 When many separate operations will need to be applied to the
306 Think carefully about whether OO is appropriate for your module.
307 Gratuitous object orientation results in complex APIs which are
308 difficult for the average module user to understand or use.
310 =head2 Designing your API
312 Your interfaces should be understandable by an average Perl programmer.
313 The following guidelines may help you judge whether your API is
314 sufficiently straightforward:
318 =item Write simple routines to do simple things.
320 It's better to have numerous simple routines than a few monolithic ones.
321 If your routine changes its behaviour significantly based on its
322 arguments, it's a sign that you should have two (or more) separate
325 =item Separate functionality from output.
327 Return your results in the most generic form possible and allow the user
328 to choose how to use them. The most generic form possible is usually a
329 Perl data structure which can then be used to generate a text report,
330 HTML, XML, a database query, or whatever else your users require.
332 If your routine iterates through some kind of list (such as a list of
333 files, or records in a database) you may consider providing a callback
334 so that users can manipulate each element of the list in turn.
335 File::Find provides an example of this with its
336 C<find(\&wanted, $dir)> syntax.
338 =item Provide sensible shortcuts and defaults.
340 Don't require every module user to jump through the same hoops to achieve a
341 simple result. You can always include optional parameters or routines for
342 more complex or non-standard behaviour. If most of your users have to
343 type a few almost identical lines of code when they start using your
344 module, it's a sign that you should have made that behaviour a default.
345 Another good indicator that you should use defaults is if most of your
346 users call your routines with the same arguments.
348 =item Naming conventions
350 Your naming should be consistent. For instance, it's better to have:
362 This applies equally to method names, parameter names, and anything else
363 which is visible to the user (and most things that aren't!)
365 =item Parameter passing
367 Use named parameters. It's easier to use a hash like this:
375 ... than to have a long list of unnamed parameters like this:
377 $obj->do_something("wibble", "text", 1024);
379 While the list of arguments might work fine for one, two or even three
380 arguments, any more arguments become hard for the module user to
381 remember, and hard for the module author to manage. If you want to add
382 a new parameter you will have to add it to the end of the list for
383 backward compatibility, and this will probably make your list order
384 unintuitive. Also, if many elements may be undefined you may see the
385 following unattractive method calls:
387 $obj->do_something(undef, undef, undef, undef, undef, undef, 1024);
389 Provide sensible defaults for parameters which have them. Don't make
390 your users specify parameters which will almost always be the same.
392 The issue of whether to pass the arguments in a hash or a hashref is
393 largely a matter of personal style.
395 The use of hash keys starting with a hyphen (C<-name>) or entirely in
396 upper case (C<NAME>) is a relic of older versions of Perl in which
397 ordinary lower case strings were not handled correctly by the C<=E<gt>>
398 operator. While some modules retain uppercase or hyphenated argument
399 keys for historical reasons or as a matter of personal style, most new
400 modules should use simple lower case keys. Whatever you choose, be
405 =head2 Strictness and warnings
407 Your module should run successfully under the strict pragma and should
408 run without generating any warnings. Your module should also handle
409 taint-checking where appropriate, though this can cause difficulties in
412 =head2 Backwards compatibility
414 Modules which are "stable" should not break backwards compatibility
415 without at least a long transition phase and a major change in version
418 =head2 Error handling and messages
420 When your module encounters an error it should do one or more of:
426 Return an undefined value.
430 set C<$Module::errstr> or similar (C<errstr> is a common name used by
431 DBI and other popular modules; if you choose something else, be sure to
432 document it clearly).
436 C<warn()> or C<carp()> a message to STDERR.
440 C<croak()> only when your module absolutely cannot figure out what to
441 do. (C<croak()> is a better version of C<die()> for use within
442 modules, which reports its errors from the perspective of the caller.
443 See L<Carp> for details of C<croak()>, C<carp()> and other useful
448 As an alternative to the above, you may prefer to throw exceptions using
453 Configurable error handling can be very useful to your users. Consider
454 offering a choice of levels for warning and debug messages, an option to
455 send messages to a separate file, a way to specify an error-handling
456 routine, or other such features. Be sure to default all these options
457 to the commonest use.
459 =head1 DOCUMENTING YOUR MODULE
463 Your module should include documentation aimed at Perl developers.
464 You should use Perl's "plain old documentation" (POD) for your general
465 technical documentation, though you may wish to write additional
466 documentation (white papers, tutorials, etc) in some other format.
467 You need to cover the following subjects:
473 A synopsis of the common uses of the module
477 The purpose, scope and target applications of your module
481 Use of each publically accessible method or subroutine, including
482 parameters and return values
490 Sources of further information
494 A contact email address for the author/maintainer
498 The level of detail in Perl module documentation generally goes from
499 less detailed to more detailed. Your SYNOPSIS section should contain a
500 minimal example of use (perhaps as little as one line of code; skip the
501 unusual use cases or anything not needed by most users); the
502 DESCRIPTION should describe your module in broad terms, generally in
503 just a few paragraphs; more detail of the module's routines or methods,
504 lengthy code examples, or other in-depth material should be given in
507 Ideally, someone who's slightly familiar with your module should be able
508 to refresh their memory without hitting "page down". As your reader
509 continues through the document, they should receive a progressively
510 greater amount of knowledge.
512 The recommended order of sections in Perl module documentation is:
530 One or more sections or subsections giving greater detail of available
531 methods and routines and any other relevant information.
547 COPYRIGHT and LICENSE
551 Keep your documentation near the code it documents ("inline"
552 documentation). Include POD for a given method right above that
553 method's subroutine. This makes it easier to keep the documentation up
554 to date, and avoids having to document each piece of code twice (once in
555 POD and once in comments).
557 =head2 README, INSTALL, release notes, changelogs
559 Your module should also include a README file describing the module and
560 giving pointers to further information (website, author email).
562 An INSTALL file should be included, and should contain simple installation
563 instructions (usually "perl Makefile.PL; make; make install").
565 Release notes or changelogs should be produced for each release of your
566 software describing user-visible changes to your module, in terms
567 relevant to the user.
569 =head1 RELEASE CONSIDERATIONS
571 =head2 Version numbering
573 Version numbers should indicate at least major and minor releases, and
574 possibly sub-minor releases. A major release is one in which most of
575 the functionality has changed, or in which major new functionality is
576 added. A minor release is one in which a small amount of functionality
577 has been added or changed. Sub-minor version numbers are usually used
578 for changes which do not affect functionality, such as documentation
581 The most common CPAN version numbering scheme looks like this:
583 1.00, 1.10, 1.11, 1.20, 1.30, 1.31, 1.32
585 A correct CPAN version number is a floating point number with at least
586 2 digits after the decimal. You can test whether it conforms to CPAN by
589 perl -MExtUtils::MakeMaker -le 'print MM->parse_version(shift)' 'Foo.pm'
591 If you want to release a 'beta' or 'alpha' version of a module but don't
592 want CPAN.pm to list it as most recent use an '_' after the regular
593 version number followed by at least 2 digits, eg. 1.20_01
595 Never release anything (even a one-word documentation patch) without
596 incrementing the number. Even a one-word documentation patch should
597 result in a change in version at the sub-minor level.
599 =head2 Pre-requisites
601 Module authors should carefully consider whether to rely on other
602 modules, and which modules to rely on.
604 Most importantly, choose modules which are as stable as possible. In
619 Unstable CPAN modules
623 Modules not available from CPAN
627 Specify version requirements for other Perl modules in the
628 pre-requisites in your Makefile.PL.
630 Be sure to specify Perl version requirements both in Makefile.PL and
631 with C<require 5.6.1> or similar.
635 All modules should be tested before distribution (using "make disttest",
636 and the tests should also be available to people installing the modules
639 The importance of these tests is proportional to the alleged stability of a
640 module -- a module which purports to be stable or which hopes to achieve wide
641 use should adhere to as strict a testing regime as possible.
643 Useful modules to help you write tests (with minimum impact on your
644 development process or your time) include Test::Simple, Carp::Assert
649 Modules should be packaged using the standard MakeMaker tools, allowing
650 them to be installed in a consistent manner. Use "make dist" to create
653 Tools exist to help you build your module in a MakeMaker-friendly style.
654 These include ExtUtils::ModuleMaker and h2xs. See also L<perlnewmod>.
658 Make sure that your module has a license, and that the full text of it
659 is included in the distribution (unless it's a common one and the terms
660 of the license don't require you to include it).
662 If you don't know what license to use, dual licensing under the GPL
663 and Artistic licenses (the same as Perl itself) is a good idea.
665 =head1 COMMON PITFALLS
667 =head2 Reinventing the wheel
669 There are certain application spaces which are already very, very well
670 served by CPAN. One example is templating systems, another is date and
671 time modules, and there are many more. While it is a rite of passage to
672 write your own version of these things, please consider carefully
673 whether the Perl world really needs you to publish it.
675 =head2 Trying to do too much
677 Your module will be part of a developer's toolkit. It will not, in
678 itself, form the B<entire> toolkit. It's tempting to add extra features
679 until your code is a monolithic system rather than a set of modular
682 =head2 Inappropriate documentation
684 Don't fall into the trap of writing for the wrong audience. Your
685 primary audience is a reasonably experienced developer with at least
686 a moderate understanding of your module's application domain, who's just
687 downloaded your module and wants to start using it as quickly as possible.
689 Tutorials, end-user documentation, research papers, FAQs etc are not
690 appropriate in a module's main documentation. If you really want to
691 write these, include them as sub-documents such as C<My::Module::Tutorial> or
692 C<My::Module::FAQ> and provide a link in the SEE ALSO section of the
701 General Perl style guide
705 How to create a new module
713 Verifies your POD's correctness
717 L<Test::Simple>, L<Test::Inline>, L<Carp::Assert>
719 =item http://pause.perl.org/
721 Perl Authors Upload Server. Contains links to information for module
724 =item Any good book on software engineering
730 Kirrily "Skud" Robert <skud@cpan.org>