One large benefit of refactoring is that it makes code more readable by humans. Machines don't care if code is ugly so long as it works, but they only have to execute it. Programmers have to review, modify, append, and delete code and easy to understand code means less problems and money. Comments are often used by coders to try to solve this problem but with refactoring comments become almost unnecessary (and often avoided).
A second benefit to refactoring is improved code maintenance. By taking large complex pieces of code and breaking them into many small pieces it becomes much easier to make changes that are easy to test and don't run the risk of breaking other parts of your app.
Refactoring also helps with things like code reuse, changing inline code to object oriented code, and implementing design patterns (the topic of the next article). Refactoring can be applied regardless of language. Changing a table based HTML site to a CSS XHTML site would even be an example of refactoring. The visual result of both is the same, but the CSS version has much easier to read and modify code.
There's a fantastic book on refactoring by Martin Fowler called Refactoring: Improving the Design of Existing Code If you want to write better code it's a must read book. He also has a website with a catalog of quite a few refactorings.
So on to a simple example:
// calculate the area of a ring with outer radius r and inner radius w
function float main(float r, float w) {
float x;
float y;
x = 3.14159 * r * r;
y = 3.14159 * w * w;
float z;
z = x - y;
return z;
}
As you can see the code would work fine, but it's both difficult to read and has some redundancy. There are many ways to refactor this, but here's an example of what I might do:
function float AreaOfRing(float outerRadius, float innerRadius) {
return AreaOfCirle(outerRadius) - AreaOfCircle(innerRadius);
}
function float AreaOfCircle(float radius) {
float PI = 3.14159;
return PI * radius * radius;
}
Hopefully you find that the refactored code is much easier to read. Plus we can use the refactored code in more ways than the original:
function float VolumeOfCylinder(float radius, float height) {
return AreaOfCirle(radius) * height;
}
This was just a basic example of a simple refactoring. You can imagine the kind of impact this technique can have on a large complex application.
There are a variety of tools out that will help you refactor your code, and there's even some methods for determining whether code needs refactored such as measuring the cyclomatic complexity of a function. With just a little effort you'll be writing cleaner code with less bugs in the same amount of time you used to spend creating spaghetti monsters.


Help

MultiQuote










