Refactoring 101
I recently inherited a QA (Quality assurance) project from another developer and been assigned to build upon it. I found the project very complicated and not very maintainable. My first thought was to completely rewrite it but this option was out of the question since this project was on the high priority list and needed to be out the door.
So what do you do? Refactoring 101
Starting from the highest level I spent my first 2 days drawing out diagrams of the database and reverse engineering the code into UML diagrams to get a better understanding of this monster. After about 3 days I had a fairly good understanding of this tightly coupled code and was ready to dive in.
My first step was to separate the business logic from the client side. .NET allows us to do this by using the code behind model.
My next step was to clean up the client side javascript code by introducing jQuery. jQuery has a very rich event related function which allow you to bind events to elements in multiple ways. The big advantage here is that you bind the events at the top of your page and make it more readable.
For example:
//bind all your events on ready
$(document).ready(function(){
$("#btnUpdateUser").click(function () {
//not implemented;
});
The code is now more readable, you don't have to jump all over the page just to see what btnUpdateUser does on a click. There is a lot more I did with jQuery but I'll leave that for another post.The heavy use of AJAX made me introduce AJAXpro to this application. AJAXpro allows you to bring server side classes with public fields to the client, the class now becomes a javascript object with properties which you can set and pass the object back to the server. Using AJAXpro I was able to bring the "User" object to the client, populate the textfields, allow the user to change the fields, repopulate the "User" javascript object and finally pass the "User" object back to the server for a database update.
Some other fundamental refactoring methods included: renaming variables to more descriptive variable names,encapsulate fields and breaking up never ending functions. Making the code more readable by breaking statements such as this one:
try { } catch(Exception Exception){} finally{};
to
try
{
}
catch (Exception Ex)
{
}
finally
{
}
Maybe it's just me but I find it much easier and much easier to read code statements from top to bottom instead of left to right.
This post was in no way intended to criticize the style of coding or practices used by the previous developer. Developers often have time constraints that don't allow for the proper design up front and a hacky simple solution had to get it out the door by the end of the week.