Thursday, January 28, 2010

Code #region considered harmful

I simply hate #regions. Apparently I'm not alone.

In C#, a bit of code surrounded in #region...#endregion markers is folded shut by any decent IDE. The code becomes invisible until you ask to see it. This sounds like a good idea, but it really is not. It makes code *look* smaller, but the code is not smaller. It is more of a girdle than a diet. The code is instead better-hidden, an attribute I can hardly describe as a virtue.

There are plenty of reasons to hate long methods and long classes. The foremost is that you cannot see and grok them at a single glance. The programmer needs to read code quickly without misunderstanding it. The #region tag is one of the most sure-fire ways to make that problem considerably worse. The region worsens most of the problems long classes and long methods cause.

The #region is almost certainly an American or British policy decision. It makes things seem better while all the time making them considerably worse. Whenever we prefer 'seeming' to 'being' we have taken a wrong turn. It is like the alcoholic who hides his booze so he can seem fine while drinking heavily in secret.

Take off the #region tags and look at your code in the clear light of day. Does it seem like it doesn't belong there? Move it instead of hiding it. Does it seem like too much boilerplate? Then cut down your framework so it demands less of you. You can make your system better, instead of hiding the dirt. Really.