When you find yourself copying two or more adjacent lines of code, and changing just a few items for each copy that you make, then those lines should be a subroutine, and the things that change from one copy to the next should be parameters to the subroutine.
When you find yourself going into a fairly deep flow-control structure of nested loops and/or conditionals, and a lot of the nested blocks involve lots of complicated code (making it hard to see what the flow-control is actually doing), then at least some of those nested blocks might be better off as subroutines, to make the "main" (outer-most) portion of the flow control more compact so that it's easier to read and comprehend.
Both of those should be used in moderation, but the first is more of a general rule that I would apply in most (if not all) cases where it's possible -- try to avoid writing the same thing more than once in a given script -- whereas the second needs to be balanced against a tendency to have too many layers of subroutines calling other subroutines that call other subroutines that ..., which can make it just as hard to keep track of what's really going on.
In any case, it helps to start with pseudo-code, laying out the algorithms and flow-control in a concise and coherent manner, and taking the time to note where a given functionality is needed at different points (i.e. should be a subroutine). And of course, when subroutine and variable names are well chosen, this helps a great deal -- the code starts to become "self documenting".
In reply to Re: when to use subroutine
by graff
in thread when to use subroutine
by convenientstore
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |