The Evils of #region
#region is nice little commenting feature in C#. Functionally, it’s a comment, but one with a balanced structure, so you enclose a section of code in a #region / #endregion pair and your editor is supposed to allow you to collapse the entire region. It can be a useful way to organize code, particularly when you want to hide boilerplate stuff that’s necessary but noisy.
The evil part is that a region, when collapsed, can hide an arbitrarily large amount of code. I was just looking at a method where the programmer had neatly wrapped up each section of the method in #region with a comment describing what was going on in that section. It made a nice little method that nearly fit onto one screen… until you expanded the regions, all 200 lines of it. That’s the dark side of #region. You can easily hide a really stinky piece of code.
Really, it gets worse. You could seriously abuse regions, doing things like this
pre.public class Foo
#region just because
{
public void Bar()
{
#endregion
}
}
It’s contrived, but the point is that regions mostly offer another way to create obfuscated code. It’s one of those things that seems useful but when I reflect on what regions are intended for, stands out more as a red flag. Being able to collapse code is a useful feature, but I think the editor should use syntax – for example, collapsing scopes around curly braces, rather than around arbitrary points in a file.
— Gordon Weakliem
Comment
Commenting is closed for this article.
Javascript Best Practices and ASP.NET The End of Presidential Elections
That’s exactly what XCode does (collapsing scopes around curly braces). Its nice, but I like being able to collapse whole sets of methods so that when I’m concentrating on one particular aspect of a class I can hide, and not have to scroll past, all the other stuff. Haven’t figured out how to do that in XCode yet.
— Nick Harris · 26 March 2009, 07:36 · #