Tuesday, November 09, 2010

Regions in C# code

Some people apparently like to put #region directives in their code, denoting which code is for constructors, which is implementations of a certain interface, etc.

I'm agin 'em.

Regions are more trouble than they're worth. True, they are useful for hiding things... but why would code need to be hidden? If implementation details are messy and hideable, extract a class to hide them. If the methods are so fractured and messy that regions are going to make a difference, then, well, regions won't make enough of a difference--it needs refactoring.

I do endorse regions around the using directives and the legal boilerplate at the top of a file, so that VS can open the file with those areas in a collapsed state. These are areas outside the type and namespace, though. Everything else in the code is presumably something I want to see, or else why would I have the file open? Don't make me do extra clicks to see what I came for.

I could consider tolerating regions as a matter of differing tastes, if people would keep them up to date. But as methods and properties get added to an interface, people write new implementations in different parts of the file from the originals. Or, common code gets extracted into helper methods. Etc. Pretty soon, the regions don't even do the one thing they're supposed to do: collect the code into areas of similarity.

Suppose some people do maintain their regions pristinely. When developers are conscientious enough to keep regions up to date, they're usually also careful enough to be writing code that doesn't need regions to clarify it. They're following the Single Responsiblity Principle, and using tests, and in general refactoring it before it reaches spaghettihood. The demographic who would be helped by regions--people who write sloppy code but are conscientious about cleaning up after themselves and are good at following rules laid down in a team's coding conventions--basically doesn't exist.

It reminds me of all the people who bought PDA's (back when there was such a category, ten years before smartphones) thinking, "Aha! Now that I have an organizer gadget, I'll get organized." It didn't happen for them. The people who were disciplined enough to keep things in their PDA's and pay attention to it, were already discplined enough to have been keeping things in their day planners. Or on pieces of damn paper. Nobody ever got a gadget to do what their personality couldn't.

In my experience, regions are all friction, no grease.