> explicitly declaring most of my variables at the top of functions
While i largely agree with the rest of your code, that one bit i can't generally agree with.
If you take care to keep all your functions below 15 or so lines, i.e. such that they fit on one screen, then that's fine.
As soon as you write bigger functions you end up impacting your code quality in two ways:
- readability and refactorability go down, because coders after you have to read more code to see the context of a variable
- the chance of bugs goes up because you're more tempted to reuse a predeclared variable in a loop, instead of redeclaring it at every start of a loop; or more insidiously, reuse the same variable as the counter in multiple loops
So please: Declare your variables as late as humanly possible, optimally only directly before they're used.
Or, if that late just isn't your style, declare a few at the beginning of each small chunk of code where they are needed. Then, guess what? You can probably easily factor that chunk out to a new function, and end up with the lots of small functions solution.
I don't disagree with your points at all. Short life variables I do tend to declare later in the code.
But most of the major state variables (especially the ones that get returned, or important data structures I want to keep track of in the code flow) I stick at the top with comments and explanations of what the variable is and why it exists.
That's better to hear. I'd still invite you to try and make a conscious efforts to make your functions smaller and more numerous. That might help you reduce the number of variables you need to make an effort to actually keep track of. :)
While i largely agree with the rest of your code, that one bit i can't generally agree with.
If you take care to keep all your functions below 15 or so lines, i.e. such that they fit on one screen, then that's fine.
As soon as you write bigger functions you end up impacting your code quality in two ways:
- readability and refactorability go down, because coders after you have to read more code to see the context of a variable
- the chance of bugs goes up because you're more tempted to reuse a predeclared variable in a loop, instead of redeclaring it at every start of a loop; or more insidiously, reuse the same variable as the counter in multiple loops
So please: Declare your variables as late as humanly possible, optimally only directly before they're used.