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