Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
Re: Thoughts on using subroutines to clean up code?by Laurent_R (Canon) |
on Mar 09, 2017 at 23:55 UTC ( [id://1184111]=note: print w/replies, xml ) | Need Help?? |
I agree with what has been said previously by other monks. Just a couple of additional thoughts.
dump out some of these edge cases to subroutines even if they will probably never be used by another bit of codeDoesn't matter. Yes, subroutines are one way to reuse code, but they serve other purposes too. For example, you can also pack edge cases into subroutines if this makes it possible to make the main flow of the program easier to follow. Or the main loop of your algorithm shorter. Don't worry if some of your subroutines get called in only one place, there is nothing wrong with that. Additional advice: your subroutines should usually have no side effect and should ideally not rely on global variables. If possible, they should be able to work alone with the parameters they get, and they should return their result. There are tenets of the functional programming paradigm, you don't have to always adhere to them fanatically (sometimes you need to use an environment variable or it make sense to use a global hash or array), but if your subroutines are functional in the sense that they rely only on input parameters and return to the caller output values, then your life will probably be easier. If only because it will be easier to test them out of context. So make your subroutines functional when possible. On the other hand, there are also some trade-offs. If you have a very large number of very small subroutines, it can also become distracting and make your program harder to follow. I have worked long ago on C++ code where almost every single line of code was a method invocation, and when you where looking at the method code, it was just another series of method invocations, and so on. This might tend to become "write-only" code: relatively easy to write, but very difficult to understand or to debug if you have to follow a dozen of nested method invocations to finally find out which piece of data is really being used or updated. So, I would say: use your judgment and good sense, it make sense to break your code into smaller subroutines (or methods), but don't overdo it either, it might become counterproductive. In short, your subroutines should not be too long, but it might also be wrong if most of them are just one or two lines long. Well, my two-cents.
In Section
Seekers of Perl Wisdom
|
|