If you are a developer it is almost certain that you had to refactor code at some point. Refactoring is no joy, especially if it is not your code and badly written.
The three code states
I like to think that the code we write can have three states:
- stable code: code that is subject to almost no changes, and at the same time permits to easily add new functionality.
- code to be refactored: this is the code that we are working on, or it is marked with @todo and a comment regarding why and what should be refactored.
- bad code: code that should be refactored, but nobody is aware of it - at least not yet... You will only notice when the client reports a bug or a feature request that cannot be implemented without changes in that portion of code.
Then, when the time comes to actually refactor the code, the question is: How do you refactor? It depends on the code that has to be refactored, but most of the time it involves moving code into a separate function, changing the structure of a classes tree or moving the implementation from a function oriented to an object oriented approach.
The five conclusions
- If possible, try to avoid having many @todos in your code, especially in the one that goes to production.
- Always write good documentation for what you have to refactor. It would be good to specify why the code has to be refactored, the priority and optionally why you've chosen not to refactor yet.
- Refactor the code as soon as possible. Ideally is in the development stage.
- Always test the new code. If you refactor it, it does not mean that that code is correct.
- Avoid writing code you know that you will have refactore it in the future.
If you are looking for a more general blog post on code refactoring you should take a look at SourceMaking's "Introduction to Refactoring".