Refactoring

There's a saying that the best way to write good code is to write it once, delete everything, and then write it again. Obviously, following this advice to the letter isn't feasible for most coding projects, but the principle is an important one. The first time through the process, you will have gained a detailed understanding of the intricacies of the problem you're trying to solve and thought through the pros and cons of numerous approaches, but chances are the code you wrote while you were learning these lessons isn't as clean as it could be.

Refactoring is the process of revising sections of code without changing its functionality. This can involve simple improvements like cleaning up inconsistencies in indentation or improving variable names, more complicated improvements like rewriting functions to be more efficient and/or cleaner, or anything in between. Refactoring is essential to writing good code, and is well worth the time.

Your goal shouldn't be to write perfect code the first time—that's just not how coding works. Instead, focus initially on writing code that does just enough to get the job done, and once you have a working version, plan to spend some quality time going through your code and refactoring. You'll invariably find that your final code is a huge improvement over the initial version, especially in terms of readability. The next person to use or adapt your code (which is often you in the future) will greatly appreciate this effort.

Refactoring is also a key component of test-driven development, which is discussed earlier in this guide.

Last Updated:
Contributors: Andrew Desautels