Most people state that regions are bad. I prefer a more fine grained definition:
Regions in code are like knives. They can cause serious injury. But a surgeon can use one to do good.
What are region intended for?
Regions provide you the ability to expand and collapse code. You can do this with members, classes and namespaces without a region. The difference is that the region keeps the collapsed state when opening a file.
There are a few problems with regions like merging in source control or the growth of classes but these are not my main pain points.
Most times I stumble across region they are used in a bad manor. On a code review today this is what showed up in the editor:
What is so bad about it? Well I like to read code and believe that reading code is really important. Therefor readability of code is important to me. It increases the maintainability. Lowers the times to understand and extend or refactor code. In short: Things that make me happy.
The regions showed force me to do unnecessary stuff, before I can read the code – I need to expand the regions, otherwise:
- I can’t see what members are contained in the class.
- I can’t read the names of the members that tell me what they do/the code does (Yes, I know – I assume that developers read the C# coding guidelines and name their stuff by using their brain).
You could argument that VS has this nice little thing that shows all members in a drop down list on the upper right corner of the editor. But I don’t want to read code in a drop down list, sorry.
I use regions
Despite of the many things on the negative side, I like regions and I use them. I believe that regions can even give you a plus on the pain point I described. I create regions to decrease the time somebody needs to read or understand code. For me a region is an abstraction. And as we all know also abstraction can be good as well as bad is used wrong. Abstracting code by wrapping member types together is contra-productive because I don’t care for instance what members are in the class. That’s only a technical perspective. On the opposite an increased productivity can be achieved by providing a layer that shows the skeleton or structure of the class. This way I can see what’s in the class from a functional perspective. If I now want to drill down into the code (after I already know what’s there) I’m forced to react. That is o.k. and my intention because the regions give me an overview and do not hide almost everything.