使用大括号来实现可变作用域是错误的吗?

发布于 2024-09-08 02:32:36 字数 1778 浏览 4 评论 0原文

我有时使用大括号来隔离代码块,以避免以后错误地使用变量。例如,当我将多个 SqlCommand 放入同一个方法中时,我经常复制粘贴代码块,最后混合名称并执行两次某些命令。添加大括号有助于避免这种情况,因为在错误的位置使用错误的 SqlCommand 会导致错误。下面是一个示例:

Collection<string> existingCategories = new Collection<string>();

// Here a beginning of a block
{
    SqlCommand getCategories = new SqlCommand("select Title from Movie.Category where SourceId = @sourceId", sqlConnection, sqlTransaction);
    getCategories.Parameters.AddWithValue("@sourceId", sourceId);
    using (SqlDataReader categoriesReader = getCategories.ExecuteReader(System.Data.CommandBehavior.SingleResult))
    {
        while (categoriesReader.Read())
        {
            existingCategories.Add(categoriesReader["Title"].ToString());
        }
    }
}

if (!existingCategories.Contains(newCategory))
{
    SqlCommand addCategory = new SqlCommand("insert into Movie.Category (SourceId, Title) values (@sourceId, @title)", sqlConnection, sqlTransaction);

    // Now try to make a mistake and write/copy-paste getCategories instead of addCategory. It will not compile.
    addCategory.Parameters.AddWithValue("@sourceId", sourceId);
    addCategory.Parameters.AddWithValue("@title", newCategory);
    addCategory.ExecuteNonQuery();
}

现在,每当块后面有一个空行时,StyleCop 就会显示一条警告。另一方面,不放置空行会使代码更难理解。

// Something like:
Collection<string> existingCategories = new Collection<string>();
{
    // Code here
}

// can be understood as (is it easy to notice that semicolon is missing?):
Collection<string> existingCategories = new Collection<string>()
{
    // Code here
}

那么,

  1. 仅出于变量作用域的目的使用大括号创建代码块是否存在问题

  2. 如果没问题,如何在不违反StyleCop规则的情况下使其更具可读性?

I sometimes use braces to isolate a block of code to avoid using by mistake a variable later. For example, when I put several SqlCommands in the same method, I frequently copy-paste blocks of code, ending by mixing the names and executing twice some commands. Adding braces helps to avoid this situation, because using a wrong SqlCommand in a wrong place will result in an error. Here's an illustration:

Collection<string> existingCategories = new Collection<string>();

// Here a beginning of a block
{
    SqlCommand getCategories = new SqlCommand("select Title from Movie.Category where SourceId = @sourceId", sqlConnection, sqlTransaction);
    getCategories.Parameters.AddWithValue("@sourceId", sourceId);
    using (SqlDataReader categoriesReader = getCategories.ExecuteReader(System.Data.CommandBehavior.SingleResult))
    {
        while (categoriesReader.Read())
        {
            existingCategories.Add(categoriesReader["Title"].ToString());
        }
    }
}

if (!existingCategories.Contains(newCategory))
{
    SqlCommand addCategory = new SqlCommand("insert into Movie.Category (SourceId, Title) values (@sourceId, @title)", sqlConnection, sqlTransaction);

    // Now try to make a mistake and write/copy-paste getCategories instead of addCategory. It will not compile.
    addCategory.Parameters.AddWithValue("@sourceId", sourceId);
    addCategory.Parameters.AddWithValue("@title", newCategory);
    addCategory.ExecuteNonQuery();
}

Now, StyleCop displays a warning every time a block follows an empty line. On the other hand, not putting an empty line would make the code much harder to understand.

// Something like:
Collection<string> existingCategories = new Collection<string>();
{
    // Code here
}

// can be understood as (is it easy to notice that semicolon is missing?):
Collection<string> existingCategories = new Collection<string>()
{
    // Code here
}

So,

  1. Is there something wrong in using braces to create blocks of code just for variable scope purposes?

  2. If it's all right, how to make it more readable without violating StyleCop rules?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

暗藏城府 2024-09-15 02:32:37

阻止代码本身并没有什么问题,但您需要考虑为什么要这样做。

如果您要复制和粘贴代码,则可能会遇到这样的情况:您应该重构代码并生成重复调用的函数,而不是重复执行相似但不同的代码块。

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.

じ违心 2024-09-15 02:32:37

使用 using 语句而不是裸括号块。

这将避免警告,并且还可以使您的代码在资源方面更加高效。

从更大的角度来看,您应该考虑将此方法拆分为更小的方法。使用一个 SqlCommand 后跟另一个 SqlCommand 通常最好的方法是调用一种方法,然后调用另一种方法。然后,每个方法将使用自己的本地 SqlCommand

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.

不美如何 2024-09-15 02:32:37

我不认为纯粹使用大括号来界定范围有什么问题——它有时非常有用。

举个例子 - 我曾经遇到过一个分析库,它使用 Profile 对象来对代码段进行计时。它们的工作原理是测量从创建到销毁的时间,因此在堆栈上创建然后在超出范围时销毁,从而测量在该特定范围内花费的时间,效果最佳。如果您想要对本身没有自己的范围的东西进行计时,那么添加额外的大括号来定义该范围可能是最好的方法。

至于可读性,我可以理解为什么 StyleCop 不喜欢它,但是任何有 C/C++/Java/C#/... 经验的人都知道大括号对定义了一个范围,并且应该相当明显,这就是你正在尝试做的事。

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.

许仙没带伞 2024-09-15 02:32:37

我认为这样的块是个好主意,我经常使用它们。当您需要将太小而无法提取到方法中的代码块分开时,或者当方法由几个彼此看起来相似但逻辑不同的代码块组成时,它非常有用。它允许给变量赋予相同的名称而不会发生命名冲突,这使得方法体更具可读性。

顺便说一句,我认为 StyleCop 有默认规则集,其中包含更多规则,其便利性值得商榷。

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.

青衫负雪 2024-09-15 02:32:37

我不得不说,如果我在你之后处理这段代码,我会对你使用范围感到有点反感。据我所知,这不是常见的做法。

我认为你这样做有一种气味。我认为更好的做法是将每个范围分解为具有完全描述性名称和文档的自己的方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文