|Keep It Simple, Stupid|
I love questions like this. So many people focus on the "how do I do X" instead of the "why do I do X". Trying to figure out the "why" has been a subject of interest to me lately and I enjoy reading the responses when these issues pop up.
A couple of simple answers (with liberal amounts of self-promotion): in this node, I was comparing and contrasting two different approaches to the same programming problem. The one that I listed on the top was how I prefer to code. The example I listed underneath was how the code often comes out. If you read through them carefully, you'll see that the difference stems, primarily, from how subroutines are used.
Generally, every subroutine should do pretty much one thing and do it well. If you have a subroutine that validates someone's username/password combination, it shouldn't also be going out and grabbing the lastest CNN headlines. Some routines, though, need to do other things. I treat them as "traffic police." I have them do as little as possible except figure out where the rest of the program is going. As a result, everything pretty much gets broken down into a series of successively smaller functions with appropriate names. Here's the main snippet from one of my programs:
Note: You can find the entire program at the bottom of this page, if you're really curious.
If you wanted, you could go down into each of the subs and figure out exactly what they do, but from just these few lines, you already have a decent idea of what the program is doing. Further, since the subroutine names are descriptive, this allows me to exclude a lot of extraneous documentation.
I think the "documentation" point is underappreciated. I'm sure you've read before about the perils of overdocumenting:
I think virtually everyone appreciates the stupidity of the above comments. If comments are needed there, they should be telling why we die if $x <= 3. However, if we have broken our program down into a successively smaller series of subroutines, and if those subroutines are appropriately named, once again the documentation issue becomes less significant:
You may not know what any of the above subs do, but you probably have a pretty good idea. Further, if you know what the output of the program is like, having things broken down like that is a gift from the powers that be.
Update: Another three points I should have made:
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
In reply to (Ovid) Re: A question about the best way to use subroutines