Should I declare variables as close as possible to

2019-06-20 08:20发布

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

7条回答
男人必须洒脱
2楼-- · 2019-06-20 08:49

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.

查看更多
登录 后发表回答