Editorials

Code Smells ? Refactoring

Yesterday I introduced the concept of “Code Smells”. Code smells are those areas of code you don’t like, but don’t have time right now to address. At the core, a code smell is some kind of code you want to refactor. So, I thought it would be helpful to talk about refactoring briefly.

Refactoring is the process of modifying code for any number of reasons:

  • Following more standardized patterns defined internally or externally
  • Making the code more easy to maintain by yourself or others
  • Improving performance
  • Moving to a newer framework
  • Moving code to a different layer
  • Implementing an abstraction for future extensibility

A good example of opportunities to refactor I see consistently in Microsoft ASP.Net Web Forms is the practice of putting all the code for a page in the code behind. It has all the data access code, presentation code, binding, Ajax, etc. all in the code behind.

While this technique works well, it enforces a number of restrictions reducing the ability for the application to scale should it become popular, or the server on which it is operating becomes too busy. A simple refactoring in this situation is to separate out your persistence into a separate DLL that may be hosted in the same process, another process on the same server, or a different process on a different server.

The point is that in this case, the data access code is difficult to split out because it is contained in the code behind. A simple refactoring is to separate out persistence activities into a separate DLL and call it from your code behind. This is a simple refactoring that can be done fairly easily, one form/method at a time, allowing for separation at a later date.

Another example I have experienced is taking advantage of the new multiple threading capabilities released in the Dot Net framework for LINQ using PLINQ (Parallel LINQ). Changing from LINQ to PLINQ allows my application to take advantage of multiple cores for better performance when it makes sense.

As a final example of refactoring I have implemented Materialized Views in the form of Data Marts for complex summary queries in order to increase performance because all the aggregation is already completed.

In databases there are lots of refactoring techniques. Scott Ambler wrote a whole book on Database Refactoring you can use as tool for learning more in this area.

Is refactoring a practice you use? Share your experience in refactoring here online or by email to btaylor@sswug.org.

Cheers,

Ben