Refactoring Code

Refactoring and Unit Testing tend to be tighly intertwined - having unit tests allows a developer to refactor with confidence, and refactoring code can make it easier to test. By this is getting a little ahead of things...

What is Refactoring

From Wikipedia...

Refactoring is the process of rewriting a computer program or other material to improve its structure or readability, while explicitly keeping its meaning or behavior.

Refactoring is simply re-organizing your code to make each function as simple as possible, while still retaining the same overall functionality of the system.

If it works, why change it?

Maintainability. Simple code is easier to understand, which makes it easier to maintain. The next obvious note is that you should only bother with this for code that you need to live with for a long time - utility libraries, applications with a long life span etc. Do not get hung up on this for quickie scripts or one-off things.

Where Do I Start?

It's very common to see large complex functions in ArcObjects code. I believe that this is due in part to how the developer thinks about the problem - as a linear series of steps. When writing code, it just follows the linear steps. A secondary reason is that with all the QI-ing around the ArcObjects model, it can seem to be a pain to pass a whole mess of objects off to another function instead of just using them in-situ.

Refactoring diagram

While this "big-ugly-function" style of coding can work, the down side is that it's very difficult maintin this type of code. It's also very difficult to test the parts of the function, and it's very very difficult to re-use portions of the code without copy-pasting (a very common, yet bad practice because you now have two places where you need to maintain code that is similar or the same).

Thus, I highly suggest adding refactoring to your coding practice. It can be done manually, but all the copy pasting & renaming can be somewhat time consuming. Luckily, there are tools to help out. If you are using Visual Studio 2005, there are some built in refactoring tools for both VB and C#. For Visual Studio 2003, there are a variety of third party tools which can help simplify the job - one that I've used (and it supports 2003 & 2005) is Refactor Pro from Developer Express. For detailed information on refactoring you can check out Refactoring.com.

Refactoring Resources