The Dot Net Campaign Against Regions
Wednesday, 30th June 2010
This is a very simple post about those nasty little things you find in .NET code files called regions. The idea behind them is that they let you organise bits of code into collapsible sections, thus making your code files look nice and tidy. In reality, this isn't what they are used for and they are one of the nastiest things you'll find! It's time to cure region-itis.
Here is an example of regions used pretty much as intended. I'm not really campaigning against this kind of usage, though I think it adds little value when almost all code editors give you the ability to collapse methods these days.
#region Public Methods // Two or three public methods here #endregion #region Private Methods // Two or three private methods here #endregion
This groups the methods into two buckets, public and private. The code editor lets you collapse these regions, so you can hide your private methods while you work on your public methods if you so wish. While I would never use ANY regions, I can understand this.
What you find more often, though, is the following example - which is an outbreak of region-itis.
#region Get A CD // A method that gets a CD #endregion #region Get A DVD // A method that gets a DVD #endregion #region Get A Download // A method that gets a Download #endregion #region Get A Book // A method that gets a Book #endregion
Essentially what we have here is just noise. Regions that just wrap a method are entirely pointless. And here's the big point of all this chat - you should only use a region if you have something meaningful to wrap up inside of it... but if you have that much code in a single file, perhaps you should be re-factoring it so each class has a more distinct responsibility... which means you actually never need to use regions because each class contains less code.