Just say No! to C# Regions

February 29, 2008

I’ve seen lots of C# code over the last few days, and 100% of it contains the #region construct. So far, I have see it used in only one way: to hide big code blocks. Some of you might be saying “Duh! That’s what they’re for!”.

Well, let’s think about that for a minute:

You need a language construct so that your IDE can help you hide your big messy code block from you (because it’s just so hideous, you don’t even want to look at it anymore)?

If your code is so bad, that you just want to shove it under the covers, then I would argue that your design and the solution to said design is too complex.

Most of the uses I’ve seen of regions are to group member fields, constructors (and related overloads), methods and properties together. This has to be the most retarded way to use a tool because you have other tools to perform this same function. Granted not everyone can buy Resharper, but the File Structure window provides all that same information. Heck, if you simply followed a simple code standard such as:

class <className>
{

  private members
  constructors
  properties
  methods

}

this would do the same job. Honestly, if you can’t LOOK at your code and tell a constructor apart from a property or field, then you should be looking for a different line of work. Please, stop commenting the obvious!

Now, you will eventually get classes that are thousands of lines long, however there are other constructs in the language that can help you keep things neat without using this lame excuse for a preprocessor tag. When you DO find your class encroaching on this large line number threshold, that is a prime time to look at your code for copy/paste refactoring tragedies and do it right. It might be a little painful now, but it could be the thing that saves your project in the long run.

Another lame way I’ve seen regions used is within a method. Usually there is a large block of setup code that is copy and pasted all over the place, with the same region tags. C’mon people, at that point, read about the Extract Method refactoring and actually REUSE that block of code intelligently!

I honestly can’t think of any reason to use #region tags because all the things they are hiding is just really bad code. When you start to just hide bad code, you are less inclined to go back and refactor it properly.

Let’s try this analogy: if you were looking to lose weight before the summer beach season, the best thing to do is get a mirror. This way, you will be re-motivated on a regular basis.

The mere act of having the bad code stare back at you will make sure that it is at least not forgotten. Nearly all codebases have some code that is not koesher. Let’s try to make that lump of code as small as possible. By then, you may even find a way to get rid of that eyesore (and system-sore) all together…after all, it was probably some hack anyway.

Advertisements