1PERLMODSTYLE(1)        Perl Programmers Reference Guide        PERLMODSTYLE(1)
2
3
4

NAME

6       perlmodstyle - Perl module style guide
7

INTRODUCTION

9       This document attempts to describe the Perl Community's "best practice"
10       for writing Perl modules.  It extends the recommendations found in
11       perlstyle , which should be considered required reading before reading
12       this document.
13
14       While this document is intended to be useful to all module authors, it
15       is particularly aimed at authors who wish to publish their modules on
16       CPAN.
17
18       The focus is on elements of style which are visible to the users of a
19       module, rather than those parts which are only seen by the module's
20       developers.  However, many of the guidelines presented in this document
21       can be extrapolated and applied successfully to a module's internals.
22
23       This document differs from perlnewmod in that it is a style guide
24       rather than a tutorial on creating CPAN modules.  It provides a check‐
25       list against which modules can be compared to determine whether they
26       conform to best practice, without necessarily describing in detail how
27       to achieve this.
28
29       All the advice contained in this document has been gleaned from exten‐
30       sive conversations with experienced CPAN authors and users.  Every
31       piece of advice given here is the result of previous mistakes.  This
32       information is here to help you avoid the same mistakes and the extra
33       work that would inevitably be required to fix them.
34
35       The first section of this document provides an itemized checklist; sub‐
36       sequent sections provide a more detailed discussion of the items on the
37       list.  The final section, "Common Pitfalls", describes some of the most
38       popular mistakes made by CPAN authors.
39

QUICK CHECKLIST

41       For more detail on each item in this checklist, see below.
42
43       Before you start
44
45       ·   Don't re-invent the wheel
46
47       ·   Patch, extend or subclass an existing module where possible
48
49       ·   Do one thing and do it well
50
51       ·   Choose an appropriate name
52
53       The API
54
55       ·   API should be understandable by the average programmer
56
57       ·   Simple methods for simple tasks
58
59       ·   Separate functionality from output
60
61       ·   Consistent naming of subroutines or methods
62
63       ·   Use named parameters (a hash or hashref) when there are more than
64           two parameters
65
66       Stability
67
68       ·   Ensure your module works under "use strict" and "-w"
69
70       ·   Stable modules should maintain backwards compatibility
71
72       Documentation
73
74       ·   Write documentation in POD
75
76       ·   Document purpose, scope and target applications
77
78       ·   Document each publically accessible method or subroutine, including
79           params and return values
80
81       ·   Give examples of use in your documentation
82
83       ·   Provide a README file and perhaps also release notes, changelog,
84           etc
85
86       ·   Provide links to further information (URL, email)
87
88       Release considerations
89
90       ·   Specify pre-requisites in Makefile.PL or Build.PL
91
92       ·   Specify Perl version requirements with "use"
93
94       ·   Include tests with your module
95
96       ·   Choose a sensible and consistent version numbering scheme (X.YY is
97           the common Perl module numbering scheme)
98
99       ·   Increment the version number for every change, no matter how small
100
101       ·   Package the module using "make dist"
102
103       ·   Choose an appropriate license (GPL/Artistic is a good default)
104

BEFORE YOU START WRITING A MODULE

106       Try not to launch headlong into developing your module without spending
107       some time thinking first.  A little forethought may save you a vast
108       amount of effort later on.
109
110       Has it been done before?
111
112       You may not even need to write the module.  Check whether it's already
113       been done in Perl, and avoid re-inventing the wheel unless you have a
114       good reason.
115
116       Good places to look for pre-existing modules include
117       http://search.cpan.org/ and asking on modules@perl.org
118
119       If an existing module almost does what you want, consider writing a
120       patch, writing a subclass, or otherwise extending the existing module
121       rather than rewriting it.
122
123       Do one thing and do it well
124
125       At the risk of stating the obvious, modules are intended to be modular.
126       A Perl developer should be able to use modules to put together the
127       building blocks of their application.  However, it's important that the
128       blocks are the right shape, and that the developer shouldn't have to
129       use a big block when all they need is a small one.
130
131       Your module should have a clearly defined scope which is no longer than
132       a single sentence.  Can your module be broken down into a family of
133       related modules?
134
135       Bad example:
136
137       "FooBar.pm provides an implementation of the FOO protocol and the
138       related BAR standard."
139
140       Good example:
141
142       "Foo.pm provides an implementation of the FOO protocol.  Bar.pm imple‐
143       ments the related BAR protocol."
144
145       This means that if a developer only needs a module for the BAR stan‐
146       dard, they should not be forced to install libraries for FOO as well.
147
148       What's in a name?
149
150       Make sure you choose an appropriate name for your module early on.
151       This will help people find and remember your module, and make program‐
152       ming with your module more intuitive.
153
154       When naming your module, consider the following:
155
156       ·   Be descriptive (i.e. accurately describes the purpose of the mod‐
157           ule).
158
159       ·   Be consistent with existing modules.
160
161       ·   Reflect the functionality of the module, not the implementation.
162
163       ·   Avoid starting a new top-level hierarchy, especially if a suitable
164           hierarchy already exists under which you could place your module.
165
166       You should contact modules@perl.org to ask them about your module name
167       before publishing your module.  You should also try to ask people who
168       are already familiar with the module's application domain and the CPAN
169       naming system.  Authors of similar modules, or modules with similar
170       names, may be a good place to start.
171

DESIGNING AND WRITING YOUR MODULE

173       Considerations for module design and coding:
174
175       To OO or not to OO?
176
177       Your module may be object oriented (OO) or not, or it may have both
178       kinds of interfaces available.  There are pros and cons of each tech‐
179       nique, which should be considered when you design your API.
180
181       According to Damian Conway, you should consider using OO:
182
183       ·   When the system is large or likely to become so
184
185       ·   When the data is aggregated in obvious structures that will become
186           objects
187
188       ·   When the types of data form a natural hierarchy that can make use
189           of inheritance
190
191       ·   When operations on data vary according to data type (making poly‐
192           morphic invocation of methods feasible)
193
194       ·   When it is likely that new data types may be later introduced into
195           the system, and will need to be handled by existing code
196
197       ·   When interactions between data are best represented by overloaded
198           operators
199
200       ·   When the implementation of system components is likely to change
201           over time (and hence should be encapsulated)
202
203       ·   When the system design is itself object-oriented
204
205       ·   When large amounts of client code will use the software (and should
206           be insulated from changes in its implementation)
207
208       ·   When many separate operations will need to be applied to the same
209           set of data
210
211       Think carefully about whether OO is appropriate for your module.  Gra‐
212       tuitous object orientation results in complex APIs which are difficult
213       for the average module user to understand or use.
214
215       Designing your API
216
217       Your interfaces should be understandable by an average Perl programmer.
218       The following guidelines may help you judge whether your API is suffi‐
219       ciently straightforward:
220
221       Write simple routines to do simple things.
222           It's better to have numerous simple routines than a few monolithic
223           ones.  If your routine changes its behaviour significantly based on
224           its arguments, it's a sign that you should have two (or more) sepa‐
225           rate routines.
226
227       Separate functionality from output.
228           Return your results in the most generic form possible and allow the
229           user to choose how to use them.  The most generic form possible is
230           usually a Perl data structure which can then be used to generate a
231           text report, HTML, XML, a database query, or whatever else your
232           users require.
233
234           If your routine iterates through some kind of list (such as a list
235           of files, or records in a database) you may consider providing a
236           callback so that users can manipulate each element of the list in
237           turn.  File::Find provides an example of this with its
238           "find(\&wanted, $dir)" syntax.
239
240       Provide sensible shortcuts and defaults.
241           Don't require every module user to jump through the same hoops to
242           achieve a simple result.  You can always include optional parame‐
243           ters or routines for more complex or non-standard behaviour.  If
244           most of your users have to type a few almost identical lines of
245           code when they start using your module, it's a sign that you should
246           have made that behaviour a default.  Another good indicator that
247           you should use defaults is if most of your users call your routines
248           with the same arguments.
249
250       Naming conventions
251           Your naming should be consistent.  For instance, it's better to
252           have:
253
254                   display_day();
255                   display_week();
256                   display_year();
257
258           than
259
260                   display_day();
261                   week_display();
262                   show_year();
263
264           This applies equally to method names, parameter names, and anything
265           else which is visible to the user (and most things that aren't!)
266
267       Parameter passing
268           Use named parameters. It's easier to use a hash like this:
269
270               $obj->do_something(
271                       name => "wibble",
272                       type => "text",
273                       size => 1024,
274               );
275
276           ... than to have a long list of unnamed parameters like this:
277
278               $obj->do_something("wibble", "text", 1024);
279
280           While the list of arguments might work fine for one, two or even
281           three arguments, any more arguments become hard for the module user
282           to remember, and hard for the module author to manage.  If you want
283           to add a new parameter you will have to add it to the end of the
284           list for backward compatibility, and this will probably make your
285           list order unintuitive.  Also, if many elements may be undefined
286           you may see the following unattractive method calls:
287
288               $obj->do_something(undef, undef, undef, undef, undef, undef, 1024);
289
290           Provide sensible defaults for parameters which have them.  Don't
291           make your users specify parameters which will almost always be the
292           same.
293
294           The issue of whether to pass the arguments in a hash or a hashref
295           is largely a matter of personal style.
296
297           The use of hash keys starting with a hyphen ("-name") or entirely
298           in upper case ("NAME") is a relic of older versions of Perl in
299           which ordinary lower case strings were not handled correctly by the
300           "=>" operator.  While some modules retain uppercase or hyphenated
301           argument keys for historical reasons or as a matter of personal
302           style, most new modules should use simple lower case keys.  What‐
303           ever you choose, be consistent!
304
305       Strictness and warnings
306
307       Your module should run successfully under the strict pragma and should
308       run without generating any warnings.  Your module should also handle
309       taint-checking where appropriate, though this can cause difficulties in
310       many cases.
311
312       Backwards compatibility
313
314       Modules which are "stable" should not break backwards compatibility
315       without at least a long transition phase and a major change in version
316       number.
317
318       Error handling and messages
319
320       When your module encounters an error it should do one or more of:
321
322       ·   Return an undefined value.
323
324       ·   set $Module::errstr or similar ("errstr" is a common name used by
325           DBI and other popular modules; if you choose something else, be
326           sure to document it clearly).
327
328       ·   "warn()" or "carp()" a message to STDERR.
329
330       ·   "croak()" only when your module absolutely cannot figure out what
331           to do.  ("croak()" is a better version of "die()" for use within
332           modules, which reports its errors from the perspective of the call‐
333           er.  See Carp for details of "croak()", "carp()" and other useful
334           routines.)
335
336       ·   As an alternative to the above, you may prefer to throw exceptions
337           using the Error module.
338
339       Configurable error handling can be very useful to your users.  Consider
340       offering a choice of levels for warning and debug messages, an option
341       to send messages to a separate file, a way to specify an error-handling
342       routine, or other such features.  Be sure to default all these options
343       to the commonest use.
344

DOCUMENTING YOUR MODULE

346       POD
347
348       Your module should include documentation aimed at Perl developers.  You
349       should use Perl's "plain old documentation" (POD) for your general
350       technical documentation, though you may wish to write additional docu‐
351       mentation (white papers, tutorials, etc) in some other format.  You
352       need to cover the following subjects:
353
354       ·   A synopsis of the common uses of the module
355
356       ·   The purpose, scope and target applications of your module
357
358       ·   Use of each publically accessible method or subroutine, including
359           parameters and return values
360
361       ·   Examples of use
362
363       ·   Sources of further information
364
365       ·   A contact email address for the author/maintainer
366
367       The level of detail in Perl module documentation generally goes from
368       less detailed to more detailed.  Your SYNOPSIS section should contain a
369       minimal example of use (perhaps as little as one line of code; skip the
370       unusual use cases or anything not needed by most users); the DESCRIP‐
371       TION should describe your module in broad terms, generally in just a
372       few paragraphs; more detail of the module's routines or methods,
373       lengthy code examples, or other in-depth material should be given in
374       subsequent sections.
375
376       Ideally, someone who's slightly familiar with your module should be
377       able to refresh their memory without hitting "page down".  As your
378       reader continues through the document, they should receive a progres‐
379       sively greater amount of knowledge.
380
381       The recommended order of sections in Perl module documentation is:
382
383       ·   NAME
384
385       ·   SYNOPSIS
386
387       ·   DESCRIPTION
388
389       ·   One or more sections or subsections giving greater detail of avail‐
390           able methods and routines and any other relevant information.
391
392       ·   BUGS/CAVEATS/etc
393
394       ·   AUTHOR
395
396       ·   SEE ALSO
397
398       ·   COPYRIGHT and LICENSE
399
400       Keep your documentation near the code it documents ("inline" documenta‐
401       tion).  Include POD for a given method right above that method's sub‐
402       routine.  This makes it easier to keep the documentation up to date,
403       and avoids having to document each piece of code twice (once in POD and
404       once in comments).
405
406       README, INSTALL, release notes, changelogs
407
408       Your module should also include a README file describing the module and
409       giving pointers to further information (website, author email).
410
411       An INSTALL file should be included, and should contain simple installa‐
412       tion instructions. When using ExtUtils::MakeMaker this will usually be:
413
414       perl Makefile.PL
415       make
416       make test
417       make install
418
419       When using Module::Build, this will usually be:
420
421       perl Build.PL
422       perl Build
423       perl Build test
424       perl Build install
425
426       Release notes or changelogs should be produced for each release of your
427       software describing user-visible changes to your module, in terms rele‐
428       vant to the user.
429

RELEASE CONSIDERATIONS

431       Version numbering
432
433       Version numbers should indicate at least major and minor releases, and
434       possibly sub-minor releases.  A major release is one in which most of
435       the functionality has changed, or in which major new functionality is
436       added.  A minor release is one in which a small amount of functionality
437       has been added or changed.  Sub-minor version numbers are usually used
438       for changes which do not affect functionality, such as documentation
439       patches.
440
441       The most common CPAN version numbering scheme looks like this:
442
443           1.00, 1.10, 1.11, 1.20, 1.30, 1.31, 1.32
444
445       A correct CPAN version number is a floating point number with at least
446       2 digits after the decimal. You can test whether it conforms to CPAN by
447       using
448
449           perl -MExtUtils::MakeMaker -le 'print MM->parse_version(shift)' 'Foo.pm'
450
451       If you want to release a 'beta' or 'alpha' version of a module but
452       don't want CPAN.pm to list it as most recent use an '_' after the regu‐
453       lar version number followed by at least 2 digits, eg. 1.20_01. If you
454       do this, the following idiom is recommended:
455
456         $VERSION = "1.12_01";
457         $XS_VERSION = $VERSION; # only needed if you have XS code
458         $VERSION = eval $VERSION;
459
460       With that trick MakeMaker will only read the first line and thus read
461       the underscore, while the perl interpreter will evaluate the $VERSION
462       and convert the string into a number. Later operations that treat $VER‐
463       SION as a number will then be able to do so without provoking a warning
464       about $VERSION not being a number.
465
466       Never release anything (even a one-word documentation patch) without
467       incrementing the number.  Even a one-word documentation patch should
468       result in a change in version at the sub-minor level.
469
470       Pre-requisites
471
472       Module authors should carefully consider whether to rely on other mod‐
473       ules, and which modules to rely on.
474
475       Most importantly, choose modules which are as stable as possible.  In
476       order of preference:
477
478       ·   Core Perl modules
479
480       ·   Stable CPAN modules
481
482       ·   Unstable CPAN modules
483
484       ·   Modules not available from CPAN
485
486       Specify version requirements for other Perl modules in the pre-requi‐
487       sites in your Makefile.PL or Build.PL.
488
489       Be sure to specify Perl version requirements both in Makefile.PL or
490       Build.PL and with "require 5.6.1" or similar. See the section on "use
491       VERSION" of "require" in perlfunc for details.
492
493       Testing
494
495       All modules should be tested before distribution (using "make
496       disttest"), and the tests should also be available to people installing
497       the modules (using "make test").  For Module::Build you would use the
498       "make test" equivalent "perl Build test".
499
500       The importance of these tests is proportional to the alleged stability
501       of a module -- a module which purports to be stable or which hopes to
502       achieve wide use should adhere to as strict a testing regime as possi‐
503       ble.
504
505       Useful modules to help you write tests (with minimum impact on your
506       development process or your time) include Test::Simple, Carp::Assert
507       and Test::Inline.  For more sophisticated test suites there are
508       Test::More and Test::MockObject.
509
510       Packaging
511
512       Modules should be packaged using one of the standard packaging tools.
513       Currently you have the choice between ExtUtils::MakeMaker and the more
514       platform independent Module::Build, allowing modules to be installed in
515       a consistent manner.  When using ExtUtils::MakeMaker, you can use "make
516       dist" to create your package. Tools exist to help you to build your
517       module in a MakeMaker-friendly style. These include ExtUtils::Module‐
518       Maker and h2xs.  See also perlnewmod.
519
520       Licensing
521
522       Make sure that your module has a license, and that the full text of it
523       is included in the distribution (unless it's a common one and the terms
524       of the license don't require you to include it).
525
526       If you don't know what license to use, dual licensing under the GPL and
527       Artistic licenses (the same as Perl itself) is a good idea.  See perl‐
528       gpl and perlartistic.
529

COMMON PITFALLS

531       Reinventing the wheel
532
533       There are certain application spaces which are already very, very well
534       served by CPAN.  One example is templating systems, another is date and
535       time modules, and there are many more.  While it is a rite of passage
536       to write your own version of these things, please consider carefully
537       whether the Perl world really needs you to publish it.
538
539       Trying to do too much
540
541       Your module will be part of a developer's toolkit.  It will not, in
542       itself, form the entire toolkit.  It's tempting to add extra features
543       until your code is a monolithic system rather than a set of modular
544       building blocks.
545
546       Inappropriate documentation
547
548       Don't fall into the trap of writing for the wrong audience.  Your pri‐
549       mary audience is a reasonably experienced developer with at least a
550       moderate understanding of your module's application domain, who's just
551       downloaded your module and wants to start using it as quickly as possi‐
552       ble.
553
554       Tutorials, end-user documentation, research papers, FAQs etc are not
555       appropriate in a module's main documentation.  If you really want to
556       write these, include them as sub-documents such as "My::Module::Tuto‐
557       rial" or "My::Module::FAQ" and provide a link in the SEE ALSO section
558       of the main documentation.
559

SEE ALSO

561       perlstyle
562           General Perl style guide
563
564       perlnewmod
565           How to create a new module
566
567       perlpod
568           POD documentation
569
570       podchecker
571           Verifies your POD's correctness
572
573       Packaging Tools
574           ExtUtils::MakeMaker, Module::Build
575
576       Testing tools
577           Test::Simple, Test::Inline, Carp::Assert, Test::More, Test::MockOb‐
578           ject
579
580       http://pause.perl.org/
581           Perl Authors Upload Server.  Contains links to information for mod‐
582           ule authors.
583
584       Any good book on software engineering
585

AUTHOR

587       Kirrily "Skud" Robert <skud@cpan.org>
588
589
590
591perl v5.8.8                       2006-01-07                   PERLMODSTYLE(1)
Impressum