As software consultants, we work in many environments. Most of the time we are working in our own environment on a brand new project, but sometimes we work with a team of client developers on existing software. In the later case, we have to be mindful of their coding standards. One practice that drives me nuts is code organized into #regions.
What’s Wrong with Regions?
Microsoft introduced #regions to help organize big files into understandable chunks. In my opinion, if your code can be broken up into regions, then it can be refactored into smaller files. I try to write my classes with single responsibility in mind, where a class has a single responsibility. Therefore regions are not required to organize the code into responsibilities.
Regions are also used to separate private, public, and protected variables, properties, and functions. This is where I see them used most often. If your class is small enough, there is no need to organize them into regions.
What makes matters worse is the way Visual Studio collapses regions by default when you open a file. This creates extra work for me, expanding all of the regions just so I can see the code. I also use incremental search in Visual Studio (Ctrl i), which fails to search in collapsed regions. This is very annoying. (FWIW, you can turn this behavior off by going to Tools – Options – Text Editor – C# – Advanced and turn off outlining mode.)
Making Regions Easy to Ignore
I recently worked for a client that required the use of #regions even if the class was very small. This bloated the code with unnecessary adornments. All I want to see is the code and not a bunch of #regions. Below is an example where one line of code is bloated into three.
I went searching for a solution. It turns out that Visual Studio has an extension appropriately named “I Hate #Regions”. It not only automatically expands the regions when you open the file, but it also changes the font size and color of the regions, so that you hardly notice that they are there. Here is the same code with I Hate #Regions turned on.
As you can see, your eyes are drawn to the code and not the regions. This extension does not modify the code in any way, so other members of the team still see the regions as they normally are. It simply changes how they are viewed in Visual Studio.