Sunday, September 09, 2007

Refactor By Region

The nature of the software development profession is such that you need to be constantly learning new techniques and improving your style. A side-effect of always seeking to be better is that when you revisit old code it suddenly doesn't seem as good as it did when you first wrote it.

I was revisiting a large class recently and was struggling to navigate between all the methods to follow the logic. I decided to make use of #region blocks (something I rarely do) to help group related methods together and hide less relevant code from view.

By arranging groups of methods together by their purpose, a pattern started to emerge. Each region started to look like an ideal candidate to refactor the code into a new class with a single responsibility. I already had a set of unit tests in place for the existing code so I felt confident in being able to refactor and being able to verify I hadn't broken anything afterward.

What was originally one class became eight, resulting in greater maintainability, testability, and of course readability, solving my original problem. For this class the refactoring by region worked well because I had grouped code by it's behaviour and partly by it's call chain.

However, I've seen other approaches to using #region blocks. I've seen all event handlers put in their own region. I've seen collections of overloaded methods grouped by name. I've even seen properties grouped together, method/subs group together, and functions grouped together. In these arrangements not only does a refactoring pattern not automatically emerge but it becomes harder to search for one.

As I mentioned above, I'm not a big user of #regions. This is probably because I try to refactor my code before it gets big enough and because of the region anti-patterns I've wrestled with. I think I might have to give them a second chance.

Comments are closed.