“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.“
This is a famous phrase from Martin Fowler and one of the most relevant motivations for refactoring. Martin defines refactoring as “a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior”. However, why should I change my piece of code if it’s perfectly running?
Well, refactoring has four main motivations:
Refactoring improve software project: Without refactoring, your software’s project start deteriorating. As more as people change it, more damaged and more difficult to understand it is. Refactoring is like putting things in their right place and helps to keep code’s quality.
Refactoring makes software easier to understand: programming is like talking with computers. When you are programming you’re telling computers what to do. However, if you talk in a difficult language, which just computers understand, the future programmer will lost a precious time trying to decode what you are telling before start creating code. Refactoring helps keeping your code more readable.
Refactoring helps finding bugs: while refactoring you’re working on code comprehension and structure. With a better code comprehension, it’s easier to look at assumptions you’ve made before and find that they were wrong.
Refactoring helps programming faster: the other three motivations result in this last one: refactoring makes you create code faster. Refactoring your code frequently makes your code ease to understand and change. So, if you have to add new functionalities, you will not need to lose time trying to figure out what that piece of code means. You go straightforward and make what have to be done quickly.
As I’ve said on the motivations, refactoring must be a programming habit. Every time you change your code, you have the responsibility to deliver it better than when you got it. So do refactoring every time you add new functions, fix a bug or review the code.
Now that you know why refactoring, you need to know how to do it. The essential thing is: have solid tests. Remember that refactoring alters program internal structure without changing its external behavior, which means you must refactor without adding new bugs. One way to guarantee that you’re not adding bugs to your project is running your tests every time you do a refactoring in your code. So, change, compile and test. Tests give you the confident to refactoring and, most of times, give you the agility to write code right and simple.
To know more about refactoring, I recommend reading Martin Fowler’s book Refactoring: Improving the Design of Existing Code. The book comes with a refactoring catalog which shows you a lot of refactoring techniques and samples; it’s really a very good reading. Now, it’s up to you.