Is it wrong to use braces for variable scope purposes?

◇◆丶佛笑我妖孽 提交于 2019-12-01 02:18:27

I don't think there's anything wrong with using braces purely to delimit scope - it can be quite useful at times.

Case in point - I came across a profiling library once that used Profile objects to time sections of code. These worked by measuring the time from their creation to destruction, and therefore worked best by being created on the stack and then being destroyed when they went out of scope, thus measuring the time spent in that particular scope. If you wanted to time something that didn't inherently have its own scope, then adding extra braces to define that scope was probably the best way to go.

As for readability, I can understand why StyleCop doesn't like it, but anyone with any experience in C/C++/Java/C#/... knows that a brace pair defines a scope, and it should be fairly evident that that's what you're trying to do.

There's nothing wrong per se with blocking off code, but you need to consider why you're doing it.

If you're copying and pasting code, you're likely in a situation where you should be refactoring the code and producing functions that you call repeatedly rather than executing similar but different blocks of code repeatedly.

Use the using statement instead of bare brace blocks.

This will avoid the warnings, and also make your code more efficient in terms of resources.

From a larger perspective, you should consider splitting up this method into smaller methods. Using one SqlCommand followed by another is usually better done by calling one method followed by another. Each method would then use their own local SqlCommand.

I think such blocks is good idea, I'm using their often. It is useful when you need to separate blocks of code that are too small to be extracted into method, or when method consists of few code blocks looks like each other, but not with the same logic. It allows to give variables the same names without naming conflicts, and this makes method body more readable.

By the way, my opinion StyleCop has default rule set with more rules which expediency is debatable.

I'd have to say if I were to work on this code after you I'd be a little offput by your use of scope. Its not, afaik, common practice.

I'd consider it a smell that you'd be doing this. I would think the better practice would be to break off each scope into its own method with fully descriptive names and documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!