in reply to Is there an ideal module size or subroutine size?

talexb:

My ideal size of a subroutine is "one thought". More specifically, a subroutine ought to be short--easy to understand when separated from the rest of your application. If it gets too large, then usually it's because you have other thoughts in there that should be split out as their own subroutines. Sometimes, however, it's long because the thought isn't naturally decomposable into multiple smaller thoughts. I can't think of an example off-hand, because I find these to be rarities.

...roboticus

  • Comment on Re: Is there an ideal module size or subroutine size?

Replies are listed 'Best First'.
Re^2: Is there an ideal module size or subroutine size?
by GrandFather (Saint) on Aug 14, 2007 at 21:01 UTC

    A state machine implementation is often done as a "switch" statement (read "if ... elsif ..." in Perl) and can get pretty long even when most of the work for each state is factored out into individual subs. There are ways to avoid the "switch" (dispatch tables for example), but often the operation of the state machine becomes less obvious.


    DWIM is Perl's answer to Gödel

      A state machine is a perfect example of what I was talking about with moving the long stuff to a data structure. Then you have a small dispatching routine and probably a long, repetitive data structure but no long code that you are trying to understand the structure of.

      I've worked a lot with state machines. With a non-trivial state machine, you don't look at the code to understand the state machine, you look at the state diagram. And the routines for each state are usually quite small, often tiny.

      For more casual state machines, factoring out the per-state actions is often important because otherwise you can't see how the states relate.

      So my guidelines for factoring out code from a state machine routine based on size are the same as for other code. And it is usually easier with state machine code because one state makes a perfect chunk to factor out.

      - tye        

      That's a very good example. When you write & document software, you don't normally use state machines. But when you do, it's because that's the best representation of that piece of the problem. And that state machine is the concept that you need to map to a subroutine, which naturally maps to a larger-than-normal subroutine. (Which thankfully has a simple, repetitive form, as you mention.)

      ...roboticus