http://qs1969.pair.com?node_id=48381

Today, I tried to write another Perl program (first one in a while tho). I spent quite a bit of time on it. But anyway, that doesn't matter, what matters (at least for this post) is what I began to debate about afterwards: When do I and when should I put my code into functions?

After thinking over it a while, I came up with several reasons why people (or maybe just me) should use functions at all:

  1. In order to decrease repetition in code by calling the same function several times instead of cutting and pasting.
  2. To clean up code to make it easier to follow and allow the reader, programmer, and debugger to find mistakes and other things they would want to alter more easily.
  3. To be able to more efficiently and quickly alter the variables used in pieces of code.

Each of these reasons has some validity and could very well be considered for use in each of those situations, however, each also has some disadvantages which I also pondered about:
  1. Loops, loops, loops. Usually in such a situation a loop will make more sense than using a function, but do not discount functions for this purpose.
  2. In order to make code easier to follow, use comments. That's what they are for, aren't they? Also, jumping from function to function can get confusing sometimes.
  3. This can be done by doing a for() loop whether it is cycling through a set of numbers ( for(my $i=0;$i<10;$i++) { ... } ) or going through an array with many random variables ( for(@array_with_many_random_variables) { ... } ).

With all of this in mind, I find that functions can help in many ways in programming in general, however, they should only be used when they are best option. In conclusion, before one puts code into a function, they should consider loops, comments, and all other possible means of achieving their goal and weigh the advantages and disadvantages of each and not making functions just to make functions. (At this point you say, "Duh, zdog! Isn't that what you should do with everything in life? Some major breakthrough... Geeze, and I just wasted a whole 1 minute and 34 seconds* reading this.")

This is what I think on the topic. What are your thoughts about it? When do you use functions?

Zenon Zabinski | zdog | Zenon.Zabinski03@students.bcp.org

*Disclaimer: The actual time it takes to read this post may vary.