Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one keenly & consciously attempt to postpone variable definitions as long as possible?

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.

like image 294
Alok Save Avatar asked Jun 21 '11 17:06

Alok Save


Video Answer


2 Answers

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.

like image 179
sbi Avatar answered Nov 04 '22 21:11

sbi


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:

  1. 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.

  2. 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

like image 27
davka Avatar answered Nov 04 '22 20:11

davka