C# Variables – Why Declare Variables Close to Where They Are Used?

cnetvariables

I have heard people say that variables should be declared as close to their usage as possible. I don't understand this.

For example, this policy would suggest I should do this:

foreach (var item in veryLongList) {
  int whereShouldIBeDeclared = item.Id;
  //...
}

But surely this means the overheads of creating a new int are incurred on every iteration. Wouldn't it be better to use:

int whereShouldIBeDeclared;
foreach (var item in veryLongList) {
  whereShouldIBeDeclared = item.Id;
  //...
}

Please could somebody explain?

Best Answer

This is one style rule among many, and it isn't necessarily the most important rule of all the possible rules you could consider. Your example, since it includes an int, isn't super compelling, but you could certainly have an expensive-to-construct object inside that loop, and perhaps a good argument for constructing the object outside the loop. However, that doesn't make it a good argument against this rule since first, there are tons of other places it could apply that don't involve constructing expensive objects in a loop, and second, a good optimizer (and you've tagged C#, so you have a good optimizer) can hoist the initialization out of the loop.

The real reason for this rule is also the reason you don't see why it's a rule. People used to write functions that were hundreds, even thousands of lines long and they used to write them in plain text editors (think Notepad) without the kind of support Visual Studio provided. In that environment, declaring a variable hundreds of lines away from where it was used meant that the person reading

if (flag) limit += factor;

didn't have a lot of clues about what flag, limit and factor were. Naming conventions like Hungarian notation were adopted to help with this, and so were rules like declaring things close to where they are used. Of course, these days, it's all about refactoring, and functions are generally less than a page long, making it hard to get very much distance between where things are declared and where they are used. You're operating in a range of 0-20 and quibbling that maybe 7 is ok in this particular instance, while the guy who made the rule would have LOVED to get 7 lines away and was trying to talk someone down from 700. And on top of that, in Visual Studio, you can mouse over anything and see its type, is it a member variable, and so on. That means the need to see the line declaring it is lessened.

It's still a reasonably good rule, one that's actually quite hard to break these days, and one that no-one ever advocated as a reason to write slow code. Be sensible, above all.

Related Topic