I feel miserable pretty much everytime I run into regions when going through C# code. Nine out of ten times, regions are the rug where developers sweep ugly code under.
Many, many years ago, I used to use regions like many people still do:
- to organize my class, grouping fields, properties, methods, etc;
- to group code according to its functionality (methods and properties related to save go here, those related to validate go there, etc.)
Eventually I finally learned that even that way of using regions was pretty bad. If a class is so big that in order to make it easier to read I need to group and hide things under regions, that means the class is doing too much. Also, if there are multiple groups of funcionality within the same class, that probably means each of those groups represent abstractions that belong somewhere else.
Now, what’s even more aggravating is using regions within method bodies. So you have code, code, code, region, code, code, region, code. I’ve seen methods that had switch-blocks where each case block had code hidden behind regions!!. If some code is within a region inside of a method body, than that code should probably be moved to a separate method!
Now, what do we make out of the example below?
The entire body of that method is hidden behind a region. What should expect to find when we expand that region? Just a few lines of the cleanest code possible, right…? Yeah, right!
If you’re using regions like that, please, take a step back and think how you can get rid of that nasty rug. 🙂