Friday, May 09, 2008

Code quality - #region directive is evil

It is, you should agree. It pollutes the code making it very difficult to read (who remembers the hotkey to Expand All?). And it doesn't help a bit.
Even if it seems to be a good idea at the time, think of how painful it will be to read the code when you (or another poor bastard) will be asked to make changes few months down the road (I barely can keep my last-week code in mind).
If one is tempted to use #region then it most likely means that a) module has grown too big to manage b) there are parts of code in the module which are irrelevant to other parts. And usually a) is directly caused by b). It doesn't mean that methods or properties from another region are completely unrelated - they just obscure reading. And #region addresses this issue very poorly. There is no reason to keep all this code in the same module - split it. It will allow to read two related pieces of code simultaneously, switching with ctrl+tab instead of scrolling back and forth, and it will make a nice, clean, better organized code. And if you think that it is too minimalistic - read about "Perfecting classes and small methods"
Code cohesiveness is the best weapon against monstrous modules. The UtilModules are evil too and I created a lot of them (and keep doing it) to know how bad they are :). UtilModule is kind of unavoidable for junk storage but still there is no excuse for the #region Database stuff - separate it to a DbUtilModule!


Chris Barrow said...

I used to believe that #region was useful, but it soon became apparent how wrong I was when I asked to look at the same code months later. Since I have never been able to remember the hotkey to expand all regions, and since by default, the find and replace function in vs2003-2005 does not search within collapsed regions, it makes maintaining code far more difficult than it has to be. I agree: if you need regions, your class/module is too big.

Unknown said...

... and thus, #region is an excellent tool for organizing your code in preparation for refactoring into smaller chunks, yes?

Michael Goldobin said...

Hmm... Maybe, if it is how you structure your refactoring. I would prefer to start kicking the bad code right away, instead of inspecting the whole application first.
Resharper, from my point of view, is a better helper here

© 2008-2013 Michael Goldobin. All rights reserved