Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare variables as close as possible to the scope where they will be used?

ReSharper usually suggests me that, and I'm still looking for a good reason of why to do that.

The only thing that came to my mind is that declaring it closer to the scope it will be used, can avoid initializing it in some cases where it isn't necessary (because a condition, etc.)

Something related with that is the following:

int temp;
foreach (var x in collection) { 
    temp = x.GetValue();
    //Do something with temp
}

Is that really different than

foreach (var x in collection) {
    int temp = x.GetValue();
    //...
}

I mean, isn't the second code more expensive because it is allocating memory everytime? Or are both the same? Of course, after finished the loop, in the second code the garbage collector will take care about temp variable, but not in the first one...

like image 918
Oscar Mederos Avatar asked May 26 '11 04:05

Oscar Mederos


People also ask

Where is the best place to declare variables?

The recommended practice is to put the declaration as close as possible to the first place where the variable is used. This also minimizes the scope. From Steve McConnell's "Code Complete" book: Ideally, declare and define each variable close to where it's first used.

Should I always declare variables?

In JavaScript, one should declare all variables at the beginning of the function to mitigate the risk of mistakes related to the fact that the scope of variables is a function.

Can we declare variable at any place?

Modern C compilers such as gcc and clang support the C99 and C11 standards, which allow you to declare a variable anywhere a statement could go. The variable's scope starts from the point of the declaration to the end of the block (next closing brace). You can also declare variables inside for loop initializers.

Why is it important to declare a variable?

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable.


6 Answers

Declaring as close as possible to use is a readability decision. Your example doesn't display it, but in longer methods it's hard to sift through the code to find the temp variable.

It's also a refactoring advantage. Declaring closer to source leads to easier refactoring later.

like image 60
Khepri Avatar answered Oct 01 '22 20:10

Khepri


The cost of the second example is negligible. The only difference is that in the first example, temp will be available outside the scope of the for loop, and thus it will exist longer than if you declared it inside the for loop.

If you don't need temp outside the for loop, it shouldn't be declared outside that loop. Like others have said, readability and style are more at play here than performance and memory.

like image 33
Cᴏʀʏ Avatar answered Oct 01 '22 20:10

Cᴏʀʏ


I agree that if you init a variable inside the scope that it's being used then you're helping the gc out, but I think the real reason is more to do with code maintenance best practices. It's sort of a way of reducing cognitive load on you or another developer coming back to the code after months (or years) of not looking at a particular block. Sure, IDE's help you discover things, but you still have to do the "go to definition" dance.

like image 20
Paul Avatar answered Oct 01 '22 19:10

Paul


There is no performance benefits, I believe, but more of a coding style. Its more C programming style to declare it all at the beginning of the scope. There is more details here: Scope of variables in C#

like image 31
M.R. Avatar answered Oct 01 '22 21:10

M.R.


Its a style personal preference thing to do with readability.

There are very few languages/systems where this will have any noticeable effect on performance.

I try to follow these two rules.

All the core attributes of a class should be defined together in one place. e.g. If you are handling an order then orderno, customerno, amount, sales tax etc. should be defined close together.

All the technical attributes which form part of the internal mechanics of the class such as iterators, flags, state varaibles should be defined close to thier usage.

Or to put it another business/external type data all defined in one place, technical/internal data defined close to usage.

like image 32
James Anderson Avatar answered Oct 01 '22 19:10

James Anderson


The difference is a matter of coding style and one of such dispute that different coding standards have completely opposite rules. The conflict is still strongest in the C++ world where the C language forced variables to be declared at the beginning of a scope and so old-timers (like myself) were well accustomed to "looking at the beginning of the function" to find variables.

The C# style that you most often see is that variables come into existence right at the point where they are needed. This style limits the existence of the variable and minimizes the chance that you could mean some other variable accidentally. I find it very easy to read.

In the modern C# era, putting the declaration of variables at their first point of use is most clearly beneficial when combined with the both loved and hated var feature. Using var just isn't that useful unless you use it with an assignment that allows the compiler and readers to infer the type of the variable. The var feature encourages declaration with first use.

Me, I love var, and so you can guess which coding style I prefer!

like image 36
Rick Sladkey Avatar answered Oct 01 '22 20:10

Rick Sladkey