Search code examples
c#javacscopecurly-braces

Why do I not see stricter scoping more often?


I've found myself limiting scope fairly often. I find it makes code much clearer, and allows me to reuse variables much more easily. This is especially handy in C where variables must be declared at the start of a new scope.

Here is an example of what I mean.

{
        int h = 0;
        foreach (var item in photos)
        {
            buffer = t.NewRow();
            h = item.IndexOf("\\x\\");
            buffer["name"] = item.Substring(h, item.Length - h);
            t.Rows.Add(buffer);
        }
}

With this example, I've limited the scope of h, without initializing it in every iteration.

But I don't see many other developers doing this very often. Why is that? Is there a downside to doing this?


Solution

  • Well, in that case you're assigning a new value in every iteration anyway, without using the "old" value - so I'd use:

    foreach (var item in photos)
    {
        buffer = t.NewRow();
        int h = item.IndexOf("\\x\\");
        buffer["name"] = item.Substring(h, item.Length - h);
        t.Rows.Add(buffer);
    }
    

    I find that if I do that as aggressively as I can (within reason, of course) I don't have much in the way of a scoping problem - and if I do, it probably means the method is too long and I should refactor it anyway.

    I dare say it can be helpful in old-style C - but when I'm writing C#, I see no reason to do things which are useful in C but don't improve my C# :)