In his book Effective C++
Scott Meyers
brings out one interesting guideline,
Item 26: Postpone variable definitions as long as possible. It increases program clarity & improves program efficiency.
The argument he puts forward to support the above is that, whenever a variable is created or destructed we incur some cost for construction & destruction of the variable.
We may have multiple control flows where in we might return from the function without making use of a variable defined early(at the beginning of the function) & thus may unnecessarily incur the cost of creation of the unused variable.
It all seems to be logical, & indeed a good practice. Coming from a c
background I have a tendency of declaring all my variable at the beginning of a function block. Maybe it is merely the c
background but I also feel having all declarations at one place in a function provides for easy & better readability.
So the question is how many of you do actually follow such a practice, in day to day programming or it is merely an overkill to attempt to follow such a practice.
Scott Meyers' advice is (as usual) very good and you should follow it. I'm doing this for two decades now, and I don't like the fact that Java has taken to the C way of doing this.
I certainly do. It indeed takes some adaptation to the new habit (coming from other languages myself I know what you mean), but once you're there, it's much more convenient. I see 2 more benefits in addition to what you mention:
improved readability: you need less "cache" in your brain to remember the variables used in the function scope. Every small peace of code defines its own variables.
initialization: it is a very important principle that variables should be defined initialized whenever possible. It is not always possible to know the initialization value at the beginning of a function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With