This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fix two broken links in perldelta.
[perl5.git] / pod / perlmodstyle.pod
1 =head1 NAME
2
3 perlmodstyle - Perl module style guide
4
5 =head1 INTRODUCTION
6
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.
11
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.
14
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.
19
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
24 how to achieve this.  
25
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.
31
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.
36
37 =head1 QUICK CHECKLIST
38
39 For more detail on each item in this checklist, see below.
40
41 =head2 Before you start
42
43 =over 4
44
45 =item *
46
47 Don't re-invent the wheel
48
49 =item *
50
51 Patch, extend or subclass an existing module where possible
52
53 =item *
54
55 Do one thing and do it well
56
57 =item *
58
59 Choose an appropriate name
60
61 =item *
62
63 Get feedback before publishing
64
65 =back
66
67 =head2 The API
68
69 =over 4
70
71 =item *
72
73 API should be understandable by the average programmer
74
75 =item *
76
77 Simple methods for simple tasks
78
79 =item *
80
81 Separate functionality from output
82
83 =item *
84
85 Consistent naming of subroutines or methods
86
87 =item *
88
89 Use named parameters (a hash or hashref) when there are more than two
90 parameters
91
92 =back
93
94 =head2 Stability
95
96 =over 4
97
98 =item *
99
100 Ensure your module works under C<use strict> and C<-w>
101
102 =item *
103
104 Stable modules should maintain backwards compatibility
105
106 =back
107
108 =head2 Documentation
109
110 =over 4
111
112 =item *
113
114 Write documentation in POD
115
116 =item *
117
118 Document purpose, scope and target applications
119
120 =item *
121
122 Document each publically accessible method or subroutine, including params and return values
123
124 =item *
125
126 Give examples of use in your documentation
127
128 =item *
129
130 Provide a README file and perhaps also release notes, changelog, etc
131
132 =item *
133
134 Provide links to further information (URL, email)
135
136 =back
137
138 =head2 Release considerations
139
140 =over 4
141
142 =item *
143
144 Specify pre-requisites in Makefile.PL or Build.PL
145
146 =item *
147
148 Specify Perl version requirements with C<use>
149
150 =item *
151
152 Include tests with your module
153
154 =item *
155
156 Choose a sensible and consistent version numbering scheme (X.YY is the common Perl module numbering scheme)
157
158 =item *
159
160 Increment the version number for every change, no matter how small
161
162 =item *
163
164 Package the module using "make dist"
165
166 =item *
167
168 Choose an appropriate license (GPL/Artistic is a good default)
169
170 =back
171
172 =head1 BEFORE YOU START WRITING A MODULE
173
174 Try not to launch headlong into developing your module without spending
175 some time thinking first.  A little forethought may save you a vast
176 amount of effort later on.
177
178 =head2 Has it been done before?
179
180 You may not even need to write the module.  Check whether it's already 
181 been done in Perl, and avoid re-inventing the wheel unless you have a 
182 good reason.
183
184 Good places to look for pre-existing modules include
185 L<http://search.cpan.org/> and L<https://metacpan.org>
186 and asking on C<module-authors@perl.org>
187 (L<http://lists.perl.org/list/module-authors.html>).
188
189 If an existing module B<almost> does what you want, consider writing a
190 patch, writing a subclass, or otherwise extending the existing module
191 rather than rewriting it.
192
193 =head2 Do one thing and do it well
194
195 At the risk of stating the obvious, modules are intended to be modular.
196 A Perl developer should be able to use modules to put together the
197 building blocks of their application.  However, it's important that the
198 blocks are the right shape, and that the developer shouldn't have to use
199 a big block when all they need is a small one.
200
201 Your module should have a clearly defined scope which is no longer than
202 a single sentence.  Can your module be broken down into a family of
203 related modules?
204
205 Bad example:
206
207 "FooBar.pm provides an implementation of the FOO protocol and the
208 related BAR standard."
209
210 Good example:
211
212 "Foo.pm provides an implementation of the FOO protocol.  Bar.pm
213 implements the related BAR protocol."
214
215 This means that if a developer only needs a module for the BAR standard,
216 they should not be forced to install libraries for FOO as well.
217
218 =head2 What's in a name?
219
220 Make sure you choose an appropriate name for your module early on.  This
221 will help people find and remember your module, and make programming
222 with your module more intuitive.
223
224 When naming your module, consider the following:
225
226 =over 4
227
228 =item *
229
230 Be descriptive (i.e. accurately describes the purpose of the module).
231
232 =item * 
233
234 Be consistent with existing modules.
235
236 =item *
237
238 Reflect the functionality of the module, not the implementation.
239
240 =item *
241
242 Avoid starting a new top-level hierarchy, especially if a suitable
243 hierarchy already exists under which you could place your module.
244
245 =back
246
247 =head2 Get feedback before publishing
248
249 If you have never uploaded a module to CPAN before (and even if you have),
250 you are strongly encouraged to get feedback on L<PrePAN|http://prepan.org>.
251 PrePAN is a site dedicated to discussing ideas for CPAN modules with other
252 Perl developers and is a great resource for new (and experienced) Perl
253 developers.
254
255 You should also try to get feedback from people who are already familiar
256 with the module's application domain and the CPAN naming system.  Authors
257 of similar modules, or modules with similar names, may be a good place to
258 start, as are community sites like L<Perl Monks|http://www.perlmonks.org>.
259
260 =head1 DESIGNING AND WRITING YOUR MODULE
261
262 Considerations for module design and coding:
263
264 =head2 To OO or not to OO?
265
266 Your module may be object oriented (OO) or not, or it may have both kinds 
267 of interfaces available.  There are pros and cons of each technique, which 
268 should be considered when you design your API.
269
270 In I<Perl Best Practices> (copyright 2004, Published by O'Reilly Media, Inc.),
271 Damian Conway provides a list of criteria to use when deciding if OO is the
272 right fit for your problem:
273
274 =over 4
275
276 =item *
277
278 The system being designed is large, or is likely to become large.
279
280 =item *
281
282 The data can be aggregated into obvious structures, especially if
283 there's a large amount of data in each aggregate.
284
285 =item *
286
287 The various types of data aggregate form a natural hierarchy that
288 facilitates the use of inheritance and polymorphism.
289
290 =item *
291
292 You have a piece of data on which many different operations are
293 applied.
294
295 =item *
296
297 You need to perform the same general operations on related types of
298 data, but with slight variations depending on the specific type of data
299 the operations are applied to.
300
301 =item *
302
303 It's likely you'll have to add new data types later.
304
305 =item *
306
307 The typical interactions between pieces of data are best represented by
308 operators.
309
310 =item *
311
312 The implementation of individual components of the system is likely to
313 change over time.
314
315 =item *
316
317 The system design is already object-oriented.
318
319 =item *
320
321 Large numbers of other programmers will be using your code modules.
322
323 =back
324
325 Think carefully about whether OO is appropriate for your module.
326 Gratuitous object orientation results in complex APIs which are
327 difficult for the average module user to understand or use.
328
329 =head2 Designing your API
330
331 Your interfaces should be understandable by an average Perl programmer.  
332 The following guidelines may help you judge whether your API is
333 sufficiently straightforward:
334
335 =over 4
336
337 =item Write simple routines to do simple things.
338
339 It's better to have numerous simple routines than a few monolithic ones.
340 If your routine changes its behaviour significantly based on its
341 arguments, it's a sign that you should have two (or more) separate
342 routines.
343
344 =item Separate functionality from output.  
345
346 Return your results in the most generic form possible and allow the user 
347 to choose how to use them.  The most generic form possible is usually a
348 Perl data structure which can then be used to generate a text report,
349 HTML, XML, a database query, or whatever else your users require.
350
351 If your routine iterates through some kind of list (such as a list of
352 files, or records in a database) you may consider providing a callback
353 so that users can manipulate each element of the list in turn.
354 File::Find provides an example of this with its 
355 C<find(\&wanted, $dir)> syntax.
356
357 =item Provide sensible shortcuts and defaults.
358
359 Don't require every module user to jump through the same hoops to achieve a
360 simple result.  You can always include optional parameters or routines for 
361 more complex or non-standard behaviour.  If most of your users have to
362 type a few almost identical lines of code when they start using your
363 module, it's a sign that you should have made that behaviour a default.
364 Another good indicator that you should use defaults is if most of your 
365 users call your routines with the same arguments.
366
367 =item Naming conventions
368
369 Your naming should be consistent.  For instance, it's better to have:
370
371         display_day();
372         display_week();
373         display_year();
374
375 than
376
377         display_day();
378         week_display();
379         show_year();
380
381 This applies equally to method names, parameter names, and anything else
382 which is visible to the user (and most things that aren't!)
383
384 =item Parameter passing
385
386 Use named parameters.  It's easier to use a hash like this:
387
388     $obj->do_something(
389             name => "wibble",
390             type => "text",
391             size => 1024,
392     );
393
394 ... than to have a long list of unnamed parameters like this:
395
396     $obj->do_something("wibble", "text", 1024);
397
398 While the list of arguments might work fine for one, two or even three
399 arguments, any more arguments become hard for the module user to
400 remember, and hard for the module author to manage.  If you want to add
401 a new parameter you will have to add it to the end of the list for
402 backward compatibility, and this will probably make your list order
403 unintuitive.  Also, if many elements may be undefined you may see the
404 following unattractive method calls:
405
406     $obj->do_something(undef, undef, undef, undef, undef, 1024);
407
408 Provide sensible defaults for parameters which have them.  Don't make
409 your users specify parameters which will almost always be the same.
410
411 The issue of whether to pass the arguments in a hash or a hashref is
412 largely a matter of personal style. 
413
414 The use of hash keys starting with a hyphen (C<-name>) or entirely in 
415 upper case (C<NAME>) is a relic of older versions of Perl in which
416 ordinary lower case strings were not handled correctly by the C<=E<gt>>
417 operator.  While some modules retain uppercase or hyphenated argument
418 keys for historical reasons or as a matter of personal style, most new
419 modules should use simple lower case keys.  Whatever you choose, be
420 consistent!
421
422 =back
423
424 =head2 Strictness and warnings
425
426 Your module should run successfully under the strict pragma and should
427 run without generating any warnings.  Your module should also handle 
428 taint-checking where appropriate, though this can cause difficulties in
429 many cases.
430
431 =head2 Backwards compatibility
432
433 Modules which are "stable" should not break backwards compatibility
434 without at least a long transition phase and a major change in version
435 number.
436
437 =head2 Error handling and messages
438
439 When your module encounters an error it should do one or more of:
440
441 =over 4
442
443 =item *
444
445 Return an undefined value.
446
447 =item *
448
449 set C<$Module::errstr> or similar (C<errstr> is a common name used by
450 DBI and other popular modules; if you choose something else, be sure to
451 document it clearly).
452
453 =item *
454
455 C<warn()> or C<carp()> a message to STDERR.  
456
457 =item *
458
459 C<croak()> only when your module absolutely cannot figure out what to
460 do.  (C<croak()> is a better version of C<die()> for use within 
461 modules, which reports its errors from the perspective of the caller.  
462 See L<Carp> for details of C<croak()>, C<carp()> and other useful
463 routines.)
464
465 =item *
466
467 As an alternative to the above, you may prefer to throw exceptions using 
468 the Error module.
469
470 =back
471
472 Configurable error handling can be very useful to your users.  Consider
473 offering a choice of levels for warning and debug messages, an option to
474 send messages to a separate file, a way to specify an error-handling
475 routine, or other such features.  Be sure to default all these options
476 to the commonest use.
477
478 =head1 DOCUMENTING YOUR MODULE
479
480 =head2 POD
481
482 Your module should include documentation aimed at Perl developers.
483 You should use Perl's "plain old documentation" (POD) for your general 
484 technical documentation, though you may wish to write additional
485 documentation (white papers, tutorials, etc) in some other format.  
486 You need to cover the following subjects:
487
488 =over 4
489
490 =item *
491
492 A synopsis of the common uses of the module
493
494 =item *
495
496 The purpose, scope and target applications of your module
497
498 =item *
499
500 Use of each publically accessible method or subroutine, including
501 parameters and return values
502
503 =item *
504
505 Examples of use
506
507 =item *
508
509 Sources of further information
510
511 =item *
512
513 A contact email address for the author/maintainer
514
515 =back
516
517 The level of detail in Perl module documentation generally goes from
518 less detailed to more detailed.  Your SYNOPSIS section should contain a
519 minimal example of use (perhaps as little as one line of code; skip the
520 unusual use cases or anything not needed by most users); the
521 DESCRIPTION should describe your module in broad terms, generally in
522 just a few paragraphs; more detail of the module's routines or methods,
523 lengthy code examples, or other in-depth material should be given in 
524 subsequent sections.
525
526 Ideally, someone who's slightly familiar with your module should be able
527 to refresh their memory without hitting "page down".  As your reader
528 continues through the document, they should receive a progressively
529 greater amount of knowledge.
530
531 The recommended order of sections in Perl module documentation is:
532
533 =over 4
534
535 =item * 
536
537 NAME
538
539 =item *
540
541 SYNOPSIS
542
543 =item *
544
545 DESCRIPTION
546
547 =item *
548
549 One or more sections or subsections giving greater detail of available 
550 methods and routines and any other relevant information.
551
552 =item *
553
554 BUGS/CAVEATS/etc
555
556 =item *
557
558 AUTHOR
559
560 =item *
561
562 SEE ALSO
563
564 =item *
565
566 COPYRIGHT and LICENSE
567
568 =back
569
570 Keep your documentation near the code it documents ("inline"
571 documentation).  Include POD for a given method right above that 
572 method's subroutine.  This makes it easier to keep the documentation up
573 to date, and avoids having to document each piece of code twice (once in
574 POD and once in comments).
575
576 =head2 README, INSTALL, release notes, changelogs
577
578 Your module should also include a README file describing the module and
579 giving pointers to further information (website, author email).  
580
581 An INSTALL file should be included, and should contain simple installation 
582 instructions.  When using ExtUtils::MakeMaker this will usually be:
583
584 =over 4
585
586 =item perl Makefile.PL
587
588 =item make
589
590 =item make test
591
592 =item make install
593
594 =back
595
596 When using Module::Build, this will usually be:
597
598 =over 4
599
600 =item perl Build.PL
601
602 =item perl Build
603
604 =item perl Build test
605
606 =item perl Build install
607
608 =back
609
610 Release notes or changelogs should be produced for each release of your
611 software describing user-visible changes to your module, in terms
612 relevant to the user.
613
614 Unless you have good reasons for using some other format
615 (for example, a format used within your company),
616 the convention is to name your changelog file C<Changes>,
617 and to follow the simple format described in L<CPAN::Changes::Spec>.
618
619 =head1 RELEASE CONSIDERATIONS
620
621 =head2 Version numbering
622
623 Version numbers should indicate at least major and minor releases, and
624 possibly sub-minor releases.  A major release is one in which most of
625 the functionality has changed, or in which major new functionality is
626 added.  A minor release is one in which a small amount of functionality
627 has been added or changed.  Sub-minor version numbers are usually used
628 for changes which do not affect functionality, such as documentation
629 patches.
630
631 The most common CPAN version numbering scheme looks like this:
632
633     1.00, 1.10, 1.11, 1.20, 1.30, 1.31, 1.32
634
635 A correct CPAN version number is a floating point number with at least 
636 2 digits after the decimal.  You can test whether it conforms to CPAN by 
637 using
638
639     perl -MExtUtils::MakeMaker -le 'print MM->parse_version(shift)' \
640                                                             'Foo.pm'
641
642 If you want to release a 'beta' or 'alpha' version of a module but
643 don't want CPAN.pm to list it as most recent use an '_' after the
644 regular version number followed by at least 2 digits, eg. 1.20_01.  If
645 you do this, the following idiom is recommended:
646
647   our $VERSION = "1.12_01"; # so CPAN distribution will have
648                             # right filename
649   our $XS_VERSION = $VERSION; # only needed if you have XS code
650   $VERSION = eval $VERSION; # so "use Module 0.002" won't warn on
651                             # underscore
652
653 With that trick MakeMaker will only read the first line and thus read
654 the underscore, while the perl interpreter will evaluate the $VERSION
655 and convert the string into a number.  Later operations that treat
656 $VERSION as a number will then be able to do so without provoking a
657 warning about $VERSION not being a number.
658
659 Never release anything (even a one-word documentation patch) without
660 incrementing the number.  Even a one-word documentation patch should
661 result in a change in version at the sub-minor level.
662
663 Once picked, it is important to stick to your version scheme, without
664 reducing the number of digits.  This is because "downstream" packagers,
665 such as the FreeBSD ports system, interpret the version numbers in
666 various ways.  If you change the number of digits in your version scheme,
667 you can confuse these systems so they get the versions of your module
668 out of order, which is obviously bad.
669
670 =head2 Pre-requisites
671
672 Module authors should carefully consider whether to rely on other
673 modules, and which modules to rely on.
674
675 Most importantly, choose modules which are as stable as possible.  In
676 order of preference: 
677
678 =over 4
679
680 =item *
681
682 Core Perl modules
683
684 =item *
685
686 Stable CPAN modules
687
688 =item *
689
690 Unstable CPAN modules
691
692 =item *
693
694 Modules not available from CPAN
695
696 =back
697
698 Specify version requirements for other Perl modules in the
699 pre-requisites in your Makefile.PL or Build.PL.
700
701 Be sure to specify Perl version requirements both in Makefile.PL or
702 Build.PL and with C<require 5.6.1> or similar.  See the section on
703 C<use VERSION> of L<perlfunc/require> for details.
704
705 =head2 Testing
706
707 All modules should be tested before distribution (using "make disttest"),
708 and the tests should also be available to people installing the modules 
709 (using "make test").  
710 For Module::Build you would use the C<make test> equivalent C<perl Build test>.
711
712 The importance of these tests is proportional to the alleged stability of a 
713 module.  A module which purports to be
714 stable or which hopes to achieve wide 
715 use should adhere to as strict a testing regime as possible.
716
717 Useful modules to help you write tests (with minimum impact on your 
718 development process or your time) include Test::Simple, Carp::Assert 
719 and Test::Inline.
720 For more sophisticated test suites there are Test::More and Test::MockObject.
721
722 =head2 Packaging
723
724 Modules should be packaged using one of the standard packaging tools.
725 Currently you have the choice between ExtUtils::MakeMaker and the
726 more platform independent Module::Build, allowing modules to be installed in a
727 consistent manner.
728 When using ExtUtils::MakeMaker, you can use "make dist" to create your
729 package.  Tools exist to help you to build your module in a
730 MakeMaker-friendly style.  These include ExtUtils::ModuleMaker and h2xs.
731 See also L<perlnewmod>.
732
733 =head2 Licensing
734
735 Make sure that your module has a license, and that the full text of it
736 is included in the distribution (unless it's a common one and the terms
737 of the license don't require you to include it).
738
739 If you don't know what license to use, dual licensing under the GPL
740 and Artistic licenses (the same as Perl itself) is a good idea.
741 See L<perlgpl> and L<perlartistic>.
742
743 =head1 COMMON PITFALLS
744
745 =head2 Reinventing the wheel
746
747 There are certain application spaces which are already very, very well
748 served by CPAN.  One example is templating systems, another is date and
749 time modules, and there are many more.  While it is a rite of passage to
750 write your own version of these things, please consider carefully
751 whether the Perl world really needs you to publish it.
752
753 =head2 Trying to do too much
754
755 Your module will be part of a developer's toolkit.  It will not, in
756 itself, form the B<entire> toolkit.  It's tempting to add extra features
757 until your code is a monolithic system rather than a set of modular
758 building blocks.
759
760 =head2 Inappropriate documentation
761
762 Don't fall into the trap of writing for the wrong audience.  Your
763 primary audience is a reasonably experienced developer with at least 
764 a moderate understanding of your module's application domain, who's just 
765 downloaded your module and wants to start using it as quickly as possible.
766
767 Tutorials, end-user documentation, research papers, FAQs etc are not 
768 appropriate in a module's main documentation.  If you really want to 
769 write these, include them as sub-documents such as C<My::Module::Tutorial> or
770 C<My::Module::FAQ> and provide a link in the SEE ALSO section of the
771 main documentation.  
772
773 =head1 SEE ALSO
774
775 =over 4
776
777 =item L<perlstyle>
778
779 General Perl style guide
780
781 =item L<perlnewmod>
782
783 How to create a new module
784
785 =item L<perlpod>
786
787 POD documentation
788
789 =item L<podchecker>
790
791 Verifies your POD's correctness
792
793 =item Packaging Tools
794
795 L<ExtUtils::MakeMaker>, L<Module::Build>
796
797 =item Testing tools
798
799 L<Test::Simple>, L<Test::Inline>, L<Carp::Assert>, L<Test::More>, L<Test::MockObject>
800
801 =item http://pause.perl.org/
802
803 Perl Authors Upload Server.  Contains links to information for module
804 authors.
805
806 =item Any good book on software engineering
807
808 =back
809
810 =head1 AUTHOR
811
812 Kirrily "Skud" Robert <skud@cpan.org>
813