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