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