coding_style1Add my vote for this tag create new tag
, view all tags

Coding Guidelines

To help build out TWiki's CodingStandards, it is useful to appreciate what is being done elsewhere. That is the purpose of this topic.

Coding Guidelines from Elsewhere



  1. The verbosity of all names should be proportional to the scope of their use
  2. The plurality of a variable name should reflect the plurality of the data it contains. In Perl, $name is a single name, while @names is an array of names
  3. In general, follow the language's conventions in variable naming and other things. If the language uses variable_names_like_this, you should too. If it uses ThisKindOfName, follow that.
  4. Failing that, use UPPER_CASE for globals, StudlyCaps for classes, and lower_case for most other things. Note the distinction between words by using either underscores or StudlyCaps.
  5. Function or subroutine names should be verbs or verb clauses. It is unnecessary to start a function name with do_.
  6. Filenames should contain underscores between words, except where they are executables in $PATH. Filenames should be all lower case, except for class files which maybe in StudlyCaps if the language's common usage dictates it.

Effective Perl Programming: Writing Better Programs with Perl (Joseph N. Hall, Randal Schwartz)



  • 1 Know your namespaces.
  • 2 Avoid using a slice when you want an element.
  • 3 Don�t assign undef when you want an empty list.
  • 4 String and numeric comparisons are different.
  • 5 Remember that 0 and �� are false.
  • 6 Understand conversions between strings and numbers.

Idiomatic Perl

  • 7 Use $_ for elegance.
  • 8 Know the other default arguments @_, @ARGV, STDIN.
  • 9 Know common shorthands and syntax quirks.
  • 10 Avoid excessive punctuation.
  • 11 Consider different ways of reading from a stream.
  • 12 Use foreach, map and grep as appropriate.
  • 13 Don�t misquote.
  • 14 Learn the myriad ways of sorting.

Regular Expressions.

  • 15 Know the precedence of regular expression operators.
  • 16 Use regular expression memory.
  • 17 Avoid greed when parsimony is best.
  • 18 Remember that whitespace is not a word boundary.
  • 19 Use split for clarity, unpack for efficiency.
  • 20 Avoid using regular expressions for simple string operations.
  • 21 Make regular expressions readable.
  • 22 Make regular expressions efficient.


  • 23 Understand the difference between my and local.
  • 24 Avoid using @_ directly - unless you have to.
  • 25 Use wantarray to write subroutines returning lists.
  • 26 Pass references instead of copies.
  • 27 Use hashes to pass named parameters.
  • 28 Use prototypes to get special argument parsing.
  • 29 Use subroutines to create other subroutines.


  • 30 Understand references and reference syntax.
  • 31 Create lists of lists with references.
  • 32 Don�t confuse anonymous arrays with list literals.
  • 33 Build C-style structs with anonymous hashes.
  • 34 Be careful with circular data structures.
  • 35 Use map and grep to manipulate complex data structures.


  • 36 Enable static and/or run-time checks.
  • 37 Use debugging and profiling modules.
  • 38 Learn to use a debugging version of Perl.
  • 39 Test things by using the debugger as a Perl shell.
  • 40 Don�t debug too much at once.

Using Packages and Modules.

  • 41 Don�t reinvent the wheel - use Perl modules.
  • 42 Understand packages and modules.
  • 43 Make sure Perl can find the modules you are using.
  • 44 Use perldoc to extract documentation for installed modules.

Writing Packages and Modules.

  • 45 Use h2xs to generate module boilerplate.
  • 46 Embed your documentation with POD.
  • 47 Use XS for low-level interfaces and/or speed.
  • 48 Submit your useful modules to the CPAN.

Object-Oriented Programming.

  • 49 Consider using Perl�s object-oriented programming features.
  • 50 Understand method inheritance in Perl.
  • 51 Inherit data explicitly.
  • 52 Create invisible interfaces with tied variables.


  • 53 Use pack and unpack for data munging.
  • 54 Know how and when to use eval, require, and do.
  • 55 Know when, and when not, to write networking code.
  • 56 Don�t forget the file test operators.
  • 57 Access the symbol table with typeglobs.
  • 58 Use @{[...]} or a tied hash to evaluate expressions inside strings.
  • 59 Initialize with BEGIN; finish with END.
  • 60 Some interesting Perl one-liners.

Writing better Perl

Perl Style - TPJ

_What is good coding practice? What is readable code? For some programmers, these questions lead to heated arguments. In the relatively young field of programming, it's natural that generally accepted rules of style and usage haven't yet emerged. Fortunately, our colleagues in the more mature field of philology (the study of language as used in literature) have set examples that we can follow. In this article, I'll describe Fathom, a module that grades the readability of Perl programs. _

BBC Perl Coding Standards

  1. You SHOULD use the standards from the �Perldoc perstyle� guide, but with some important differences as discussed here.
  • A4 You SHOULD use subroutines, which are no longer than 100 lines, wherever possible. A subroutine longer than that SHOULD be refactored, as this is likely to make it clearer and easier to maintain.
  • A8 We use the case of variable names to show their scope
  • A10 You MUST use single quotes where interpolation is not required, because they are more efficient.
  • A12 You MUST NOT put markup language in code. CPAN provides several good templating modules, and a stripped-down version of an HTML::Template (called BBC::CGI::Template) can also be used. There should not be any situation where you need to put HTML or other markup into Perl code.
  • http://www.bbc.co.uk/guidelines/webdev/AppA.Perl_Coding_Standards.htm


  • No & in function call unless necessary.


Perl Monks

  1. use strict and warnings
  2. use HTML::Template not HERE documents
  3. no deliberate obfuscation
  4. all files must be documented with POD (Author, Date created, synopsis, description)
  5. OO always to be used where possible
  6. Pass by reference
  7. No hardcoding of values especially file paths, script names etc
  8. Config files or config scripts to be used
  9. Do not reinvent wheel always check CPAN
  10. minimise coupling
  11. maximise cohesion
  12. maximise reuse
  13. Always indent logic
  14. Any reused code block above 5 lines must become a sub routine
  15. Always retrieve database rows into hash reference not arrays
  16. Use CGI CARP
  17. Assign CGI parameters to hashes
  18. Version history at bottom of file
  19. All subroutines to be commented
  20. Meaningful Subroutine and Variable names to be used
  21. Constructors must only create objects
  22. Program flow control to be places in 'main' method
  23. No Global Variables
  24. use my not local
  25. All Perl filehandles should be in all uppercase
  26. Always use CGIpm
  27. Use verbs for subroutines, use nouns for variables, be descriptive and consistent
  28. Do not use $_
  29. Do no use goto
  30. Initialise variables
  31. Error handling done using Begin blocks at CGI level All dies are logged
  32. Where code returns a result it should do so or die with a meaningful error and $!

So many standards to choose from...


-- MartinCleaver - 16 Oct 2004

The Coad Letter: Test-driven Development, Issue 106, Intentional Coding, by Dave Astels

From http://bdn.borland.com/article/0,1410,29608,00.html :

There are several patterns that we can use when choosing names:

  • Nouns or noun phrases for class names
Name classes for what they represent or what they do, e.g. Movie, Review, or MovieRatingComparator.

  • Either nouns, noun phrases, or adjectives for interfaces
Interfaces are a bit different. If an adjective is used for an interface name, it usually ends with -able, e.g. Runnable, Serializable. My advice is to avoid conventions that prepend or append I to the name.

  • Verbs and verb phrases for method names
Methods do something, therefore using verbs to name them makes sense. Examples include isEmpty, addMovie, fetchReview.

  • Nouns and noun phrases for variable names
Variables hold things, so nouns make sense, e.g. rating, movies, connectionToReviewServer.

"No Comment"

There are valid reasons to write comments. We'll talk about these later. However, most comments are not written for valid reasons. Fowler's Refactoring[2] calls comments "deodorant"...they are there to try to hide the bad smell of the code. The code is unclear, the code is poorly written, names are badly chosen, the logic is obtuse, etc. Comments were added to try to explain what the code does. The code should have been, and should be, refactored to make the comments unnecessary.

Don't get me wrong. I'm not saying "Don't write documentation." Nobody really doing XP will say that. Sometimes it is important to the customer to have specific documentation written. Also, I'm not saying "Never write comments." What I am saying is "Never write unnecessary comments." Most comments are unnecessary if the code is written so that the intent is clear. If and when we do write comments, we need to make sure they communicate why and not how.

Valid Comments

As I mentioned above, there are several valid reasons for us to write comments.

Incomplete code

This type of comment serves as a note to what we were in the midst of working on, or how we see the code evolving. There generally is not much need for this type of comment, since tasks should be no larger than what can be accomplished in a single day. A valid use for this type of comment might be to note code that could benefit from being refactored. Maybe we saw the need to refactor but didn't have time to do it. Make a note so that someone will spot it and do the refactoring when there is time. It might be prudent to use standard wording for these "refactoring TODO" comments so that a global search can be performed as a rough code-debt metric.

Refactoring doesn't make it clear enough

This isn't really a valid comment, rather it is more like the previous type...it's an IOU. If refactoring doesn't clean up the code, either someone else should try their hand at it, or (more likely) the code in question should be scrapped and rewritten.

Use of an unusual algorithm

If we use an uncommon algorithm for some reason, we should make a note of it with a comment. Point the reader to where they can learn more. Don't try to document the algorithm in a huge comment. Just note what algorithm it is, why it was used, and where to find more information.

Use of a published algorithm

If we use an algorithm that is published somewhere, we should add a comment saying where and giving credit to the author. This type of comment is often used with the previous type.

Performance tuning

This is important. If we tune for performance, we should add a comment explaining it. At the very least we need to add a note saying that the method in question has been tuned. If we tune without adding a note making it known we may find that someone later refactors to make the code clearer, undoing the optimization in the process. Keep in mind that we generally shouldn't be performance tuning until late in the project, once performance has been measured and bottlenecks have been found. There are times when a certain level of performance has business value. When this is the case, that value will determine when you should work on the performance. There are extensions to JUnit (e.g. JUnitPerf) that you can use to test-drive performance tuning.

Class comment

This is the one case that should always be adhered to, in spite of the general disapproval of comments. Classes and interfaces should always be commented. Not much is required. A simple note at the beginning of the class briefly explaining why the class exists and what it is used for will suffice. Avoid writing a how to use this class tutorial. That's one of the things the tests are for.

-- Contributors: MartinCleaver


-- MartinCleaver - 05 Jun 2006

Edit | Attach | Watch | Print version | History: r2 < r1 | Backlinks | Raw View | Raw edit | More topic actions
Topic revision: r2 - 2008-09-14 - TWikiJanitor
  • Learn about TWiki  
  • Download TWiki
This site is powered by the TWiki collaboration platform Powered by Perl Hosted by OICcam.com Ideas, requests, problems regarding TWiki? Send feedback. Ask community in the support forum.
Copyright © 1999-2018 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.