in reply to when to use subroutine

If it makes sense to give a chunk of code a name that describes what the code does in a succinct fashion then the code should probably be in a sub.

If the same sequence of steps is performed in multiple places, they should be in a sub.

Breaking code up into subs does a few things for you. It:

  1. makes program flow clearer
  2. documents expected behavior
  3. makes testing easier
  4. reduces development time
  5. makes debugging easier

There is a rule of thumb that says "a sub should fix on a page (of whatever media you use)" which is a slightly useful guide in that anything much bigger than a page you probably can't understand easily as a unit, so should break up in to smaller pieces (subs). It's ok as a guide, but the more important driver is that it makes sense for the code in the sub to be treated as an entity. It's a little like breaking a web page into a number of nested pages where you don't have to follow all the links to make sense of the top page, but if you want the detail, follow the links.


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: when to use subroutine
by doom (Deacon) on Oct 29, 2007 at 06:54 UTC
    makes testing easier

    I was waiting for someone to say that. If you put a chunk of code in a sub, and then move the sub to a module, you can write automated tests that verify that that sub does what you think that it does (and they can be run again at any time to verify that it hasn't broken for some reason since you last looked at it).

    Sharing code and improving clarity are important, but making sure the code works is important also: if you can break any bit of functionality out into a sub, it becomes possible to test it to make sure it really does function.

    (It might be better if you started reversing the sense of the question: "Is there any reason I shouldn't put this piece of code into a sub?")