1PERLMODSTYLE(1) Perl Programmers Reference Guide PERLMODSTYLE(1)
2
3
4
6 perlmodstyle - Perl module style guide
7
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
25 checklist against which modules can be compared to determine whether
26 they conform to best practice, without necessarily describing in detail
27 how to achieve this.
28
29 All the advice contained in this document has been gleaned from
30 extensive 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;
36 subsequent sections provide a more detailed discussion of the items on
37 the list. The final section, "Common Pitfalls", describes some of the
38 most popular mistakes made by CPAN authors.
39
41 For more detail on each item in this checklist, see below.
42
43 Before you start
44 · Don't re-invent the wheel
45
46 · Patch, extend or subclass an existing module where possible
47
48 · Do one thing and do it well
49
50 · Choose an appropriate name
51
52 The API
53 · API should be understandable by the average programmer
54
55 · Simple methods for simple tasks
56
57 · Separate functionality from output
58
59 · Consistent naming of subroutines or methods
60
61 · Use named parameters (a hash or hashref) when there are more than
62 two parameters
63
64 Stability
65 · Ensure your module works under "use strict" and "-w"
66
67 · Stable modules should maintain backwards compatibility
68
69 Documentation
70 · Write documentation in POD
71
72 · Document purpose, scope and target applications
73
74 · Document each publically accessible method or subroutine, including
75 params and return values
76
77 · Give examples of use in your documentation
78
79 · Provide a README file and perhaps also release notes, changelog,
80 etc
81
82 · Provide links to further information (URL, email)
83
84 Release considerations
85 · Specify pre-requisites in Makefile.PL or Build.PL
86
87 · Specify Perl version requirements with "use"
88
89 · Include tests with your module
90
91 · Choose a sensible and consistent version numbering scheme (X.YY is
92 the common Perl module numbering scheme)
93
94 · Increment the version number for every change, no matter how small
95
96 · Package the module using "make dist"
97
98 · Choose an appropriate license (GPL/Artistic is a good default)
99
101 Try not to launch headlong into developing your module without spending
102 some time thinking first. A little forethought may save you a vast
103 amount of effort later on.
104
105 Has it been done before?
106 You may not even need to write the module. Check whether it's already
107 been done in Perl, and avoid re-inventing the wheel unless you have a
108 good reason.
109
110 Good places to look for pre-existing modules include
111 http://search.cpan.org/ and asking on modules@perl.org
112
113 If an existing module almost does what you want, consider writing a
114 patch, writing a subclass, or otherwise extending the existing module
115 rather than rewriting it.
116
117 Do one thing and do it well
118 At the risk of stating the obvious, modules are intended to be modular.
119 A Perl developer should be able to use modules to put together the
120 building blocks of their application. However, it's important that the
121 blocks are the right shape, and that the developer shouldn't have to
122 use a big block when all they need is a small one.
123
124 Your module should have a clearly defined scope which is no longer than
125 a single sentence. Can your module be broken down into a family of
126 related modules?
127
128 Bad example:
129
130 "FooBar.pm provides an implementation of the FOO protocol and the
131 related BAR standard."
132
133 Good example:
134
135 "Foo.pm provides an implementation of the FOO protocol. Bar.pm
136 implements the related BAR protocol."
137
138 This means that if a developer only needs a module for the BAR
139 standard, they should not be forced to install libraries for FOO as
140 well.
141
142 What's in a name?
143 Make sure you choose an appropriate name for your module early on.
144 This will help people find and remember your module, and make
145 programming with your module more intuitive.
146
147 When naming your module, consider the following:
148
149 · Be descriptive (i.e. accurately describes the purpose of the
150 module).
151
152 · Be consistent with existing modules.
153
154 · Reflect the functionality of the module, not the implementation.
155
156 · Avoid starting a new top-level hierarchy, especially if a suitable
157 hierarchy already exists under which you could place your module.
158
159 You should contact modules@perl.org to ask them about your module name
160 before publishing your module. You should also try to ask people who
161 are already familiar with the module's application domain and the CPAN
162 naming system. Authors of similar modules, or modules with similar
163 names, may be a good place to start.
164
166 Considerations for module design and coding:
167
168 To OO or not to OO?
169 Your module may be object oriented (OO) or not, or it may have both
170 kinds of interfaces available. There are pros and cons of each
171 technique, which should be considered when you design your API.
172
173 According to Damian Conway, you should consider using OO:
174
175 · When the system is large or likely to become so
176
177 · When the data is aggregated in obvious structures that will become
178 objects
179
180 · When the types of data form a natural hierarchy that can make use
181 of inheritance
182
183 · When operations on data vary according to data type (making
184 polymorphic invocation of methods feasible)
185
186 · When it is likely that new data types may be later introduced into
187 the system, and will need to be handled by existing code
188
189 · When interactions between data are best represented by overloaded
190 operators
191
192 · When the implementation of system components is likely to change
193 over time (and hence should be encapsulated)
194
195 · When the system design is itself object-oriented
196
197 · When large amounts of client code will use the software (and should
198 be insulated from changes in its implementation)
199
200 · When many separate operations will need to be applied to the same
201 set of data
202
203 Think carefully about whether OO is appropriate for your module.
204 Gratuitous object orientation results in complex APIs which are
205 difficult for the average module user to understand or use.
206
207 Designing your API
208 Your interfaces should be understandable by an average Perl programmer.
209 The following guidelines may help you judge whether your API is
210 sufficiently straightforward:
211
212 Write simple routines to do simple things.
213 It's better to have numerous simple routines than a few monolithic
214 ones. If your routine changes its behaviour significantly based on
215 its arguments, it's a sign that you should have two (or more)
216 separate routines.
217
218 Separate functionality from output.
219 Return your results in the most generic form possible and allow the
220 user to choose how to use them. The most generic form possible is
221 usually a Perl data structure which can then be used to generate a
222 text report, HTML, XML, a database query, or whatever else your
223 users require.
224
225 If your routine iterates through some kind of list (such as a list
226 of files, or records in a database) you may consider providing a
227 callback so that users can manipulate each element of the list in
228 turn. File::Find provides an example of this with its
229 "find(\&wanted, $dir)" syntax.
230
231 Provide sensible shortcuts and defaults.
232 Don't require every module user to jump through the same hoops to
233 achieve a simple result. You can always include optional
234 parameters or routines for more complex or non-standard behaviour.
235 If most of your users have to type a few almost identical lines of
236 code when they start using your module, it's a sign that you should
237 have made that behaviour a default. Another good indicator that
238 you should use defaults is if most of your users call your routines
239 with the same arguments.
240
241 Naming conventions
242 Your naming should be consistent. For instance, it's better to
243 have:
244
245 display_day();
246 display_week();
247 display_year();
248
249 than
250
251 display_day();
252 week_display();
253 show_year();
254
255 This applies equally to method names, parameter names, and anything
256 else which is visible to the user (and most things that aren't!)
257
258 Parameter passing
259 Use named parameters. It's easier to use a hash like this:
260
261 $obj->do_something(
262 name => "wibble",
263 type => "text",
264 size => 1024,
265 );
266
267 ... than to have a long list of unnamed parameters like this:
268
269 $obj->do_something("wibble", "text", 1024);
270
271 While the list of arguments might work fine for one, two or even
272 three arguments, any more arguments become hard for the module user
273 to remember, and hard for the module author to manage. If you want
274 to add a new parameter you will have to add it to the end of the
275 list for backward compatibility, and this will probably make your
276 list order unintuitive. Also, if many elements may be undefined
277 you may see the following unattractive method calls:
278
279 $obj->do_something(undef, undef, undef, undef, undef, undef, 1024);
280
281 Provide sensible defaults for parameters which have them. Don't
282 make your users specify parameters which will almost always be the
283 same.
284
285 The issue of whether to pass the arguments in a hash or a hashref
286 is largely a matter of personal style.
287
288 The use of hash keys starting with a hyphen ("-name") or entirely
289 in upper case ("NAME") is a relic of older versions of Perl in
290 which ordinary lower case strings were not handled correctly by the
291 "=>" operator. While some modules retain uppercase or hyphenated
292 argument keys for historical reasons or as a matter of personal
293 style, most new modules should use simple lower case keys.
294 Whatever you choose, be consistent!
295
296 Strictness and warnings
297 Your module should run successfully under the strict pragma and should
298 run without generating any warnings. Your module should also handle
299 taint-checking where appropriate, though this can cause difficulties in
300 many cases.
301
302 Backwards compatibility
303 Modules which are "stable" should not break backwards compatibility
304 without at least a long transition phase and a major change in version
305 number.
306
307 Error handling and messages
308 When your module encounters an error it should do one or more of:
309
310 · Return an undefined value.
311
312 · set $Module::errstr or similar ("errstr" is a common name used by
313 DBI and other popular modules; if you choose something else, be
314 sure to document it clearly).
315
316 · "warn()" or "carp()" a message to STDERR.
317
318 · "croak()" only when your module absolutely cannot figure out what
319 to do. ("croak()" is a better version of "die()" for use within
320 modules, which reports its errors from the perspective of the
321 caller. See Carp for details of "croak()", "carp()" and other
322 useful routines.)
323
324 · As an alternative to the above, you may prefer to throw exceptions
325 using the Error module.
326
327 Configurable error handling can be very useful to your users. Consider
328 offering a choice of levels for warning and debug messages, an option
329 to send messages to a separate file, a way to specify an error-handling
330 routine, or other such features. Be sure to default all these options
331 to the commonest use.
332
334 POD
335 Your module should include documentation aimed at Perl developers. You
336 should use Perl's "plain old documentation" (POD) for your general
337 technical documentation, though you may wish to write additional
338 documentation (white papers, tutorials, etc) in some other format. You
339 need to cover the following subjects:
340
341 · A synopsis of the common uses of the module
342
343 · The purpose, scope and target applications of your module
344
345 · Use of each publically accessible method or subroutine, including
346 parameters and return values
347
348 · Examples of use
349
350 · Sources of further information
351
352 · A contact email address for the author/maintainer
353
354 The level of detail in Perl module documentation generally goes from
355 less detailed to more detailed. Your SYNOPSIS section should contain a
356 minimal example of use (perhaps as little as one line of code; skip the
357 unusual use cases or anything not needed by most users); the
358 DESCRIPTION should describe your module in broad terms, generally in
359 just a few paragraphs; more detail of the module's routines or methods,
360 lengthy code examples, or other in-depth material should be given in
361 subsequent sections.
362
363 Ideally, someone who's slightly familiar with your module should be
364 able to refresh their memory without hitting "page down". As your
365 reader continues through the document, they should receive a
366 progressively greater amount of knowledge.
367
368 The recommended order of sections in Perl module documentation is:
369
370 · NAME
371
372 · SYNOPSIS
373
374 · DESCRIPTION
375
376 · One or more sections or subsections giving greater detail of
377 available methods and routines and any other relevant information.
378
379 · BUGS/CAVEATS/etc
380
381 · AUTHOR
382
383 · SEE ALSO
384
385 · COPYRIGHT and LICENSE
386
387 Keep your documentation near the code it documents ("inline"
388 documentation). Include POD for a given method right above that
389 method's subroutine. This makes it easier to keep the documentation up
390 to date, and avoids having to document each piece of code twice (once
391 in POD and once in comments).
392
393 README, INSTALL, release notes, changelogs
394 Your module should also include a README file describing the module and
395 giving pointers to further information (website, author email).
396
397 An INSTALL file should be included, and should contain simple
398 installation instructions. When using ExtUtils::MakeMaker this will
399 usually be:
400
401 perl Makefile.PL
402 make
403 make test
404 make install
405
406 When using Module::Build, this will usually be:
407
408 perl Build.PL
409 perl Build
410 perl Build test
411 perl Build install
412
413 Release notes or changelogs should be produced for each release of your
414 software describing user-visible changes to your module, in terms
415 relevant to the user.
416
418 Version numbering
419 Version numbers should indicate at least major and minor releases, and
420 possibly sub-minor releases. A major release is one in which most of
421 the functionality has changed, or in which major new functionality is
422 added. A minor release is one in which a small amount of functionality
423 has been added or changed. Sub-minor version numbers are usually used
424 for changes which do not affect functionality, such as documentation
425 patches.
426
427 The most common CPAN version numbering scheme looks like this:
428
429 1.00, 1.10, 1.11, 1.20, 1.30, 1.31, 1.32
430
431 A correct CPAN version number is a floating point number with at least
432 2 digits after the decimal. You can test whether it conforms to CPAN by
433 using
434
435 perl -MExtUtils::MakeMaker -le 'print MM->parse_version(shift)' 'Foo.pm'
436
437 If you want to release a 'beta' or 'alpha' version of a module but
438 don't want CPAN.pm to list it as most recent use an '_' after the
439 regular version number followed by at least 2 digits, eg. 1.20_01. If
440 you do this, the following idiom is recommended:
441
442 $VERSION = "1.12_01";
443 $XS_VERSION = $VERSION; # only needed if you have XS code
444 $VERSION = eval $VERSION;
445
446 With that trick MakeMaker will only read the first line and thus read
447 the underscore, while the perl interpreter will evaluate the $VERSION
448 and convert the string into a number. Later operations that treat
449 $VERSION as a number will then be able to do so without provoking a
450 warning about $VERSION not being a number.
451
452 Never release anything (even a one-word documentation patch) without
453 incrementing the number. Even a one-word documentation patch should
454 result in a change in version at the sub-minor level.
455
456 Pre-requisites
457 Module authors should carefully consider whether to rely on other
458 modules, and which modules to rely on.
459
460 Most importantly, choose modules which are as stable as possible. In
461 order of preference:
462
463 · Core Perl modules
464
465 · Stable CPAN modules
466
467 · Unstable CPAN modules
468
469 · Modules not available from CPAN
470
471 Specify version requirements for other Perl modules in the pre-
472 requisites in your Makefile.PL or Build.PL.
473
474 Be sure to specify Perl version requirements both in Makefile.PL or
475 Build.PL and with "require 5.6.1" or similar. See the section on "use
476 VERSION" of "require" in perlfunc for details.
477
478 Testing
479 All modules should be tested before distribution (using "make
480 disttest"), and the tests should also be available to people installing
481 the modules (using "make test"). For Module::Build you would use the
482 "make test" equivalent "perl Build test".
483
484 The importance of these tests is proportional to the alleged stability
485 of a module -- a module which purports to be stable or which hopes to
486 achieve wide use should adhere to as strict a testing regime as
487 possible.
488
489 Useful modules to help you write tests (with minimum impact on your
490 development process or your time) include Test::Simple, Carp::Assert
491 and Test::Inline. For more sophisticated test suites there are
492 Test::More and Test::MockObject.
493
494 Packaging
495 Modules should be packaged using one of the standard packaging tools.
496 Currently you have the choice between ExtUtils::MakeMaker and the more
497 platform independent Module::Build, allowing modules to be installed in
498 a consistent manner. When using ExtUtils::MakeMaker, you can use "make
499 dist" to create your package. Tools exist to help you to build your
500 module in a MakeMaker-friendly style. These include
501 ExtUtils::ModuleMaker and h2xs. See also perlnewmod.
502
503 Licensing
504 Make sure that your module has a license, and that the full text of it
505 is included in the distribution (unless it's a common one and the terms
506 of the license don't require you to include it).
507
508 If you don't know what license to use, dual licensing under the GPL and
509 Artistic licenses (the same as Perl itself) is a good idea. See
510 perlgpl and perlartistic.
511
513 Reinventing the wheel
514 There are certain application spaces which are already very, very well
515 served by CPAN. One example is templating systems, another is date and
516 time modules, and there are many more. While it is a rite of passage
517 to write your own version of these things, please consider carefully
518 whether the Perl world really needs you to publish it.
519
520 Trying to do too much
521 Your module will be part of a developer's toolkit. It will not, in
522 itself, form the entire toolkit. It's tempting to add extra features
523 until your code is a monolithic system rather than a set of modular
524 building blocks.
525
526 Inappropriate documentation
527 Don't fall into the trap of writing for the wrong audience. Your
528 primary audience is a reasonably experienced developer with at least a
529 moderate understanding of your module's application domain, who's just
530 downloaded your module and wants to start using it as quickly as
531 possible.
532
533 Tutorials, end-user documentation, research papers, FAQs etc are not
534 appropriate in a module's main documentation. If you really want to
535 write these, include them as sub-documents such as
536 "My::Module::Tutorial" or "My::Module::FAQ" and provide a link in the
537 SEE ALSO section of the main documentation.
538
540 perlstyle
541 General Perl style guide
542
543 perlnewmod
544 How to create a new module
545
546 perlpod
547 POD documentation
548
549 podchecker
550 Verifies your POD's correctness
551
552 Packaging Tools
553 ExtUtils::MakeMaker, Module::Build
554
555 Testing tools
556 Test::Simple, Test::Inline, Carp::Assert, Test::More,
557 Test::MockObject
558
559 http://pause.perl.org/
560 Perl Authors Upload Server. Contains links to information for
561 module authors.
562
563 Any good book on software engineering
564
566 Kirrily "Skud" Robert <skud@cpan.org>
567
568
569
570perl v5.10.1 2009-02-12 PERLMODSTYLE(1)