I once worked for a client whose developers would sometimes embark on what they called refactoring.
These developers had an interesting conception of what refactoring was. To them, refactoring was when you experimented with new design patterns. Sometimes the behavior of the “refactored” code would stay the same and sometimes it would change.
Refactoring is when you change the design of existing code without changing its behavior. And in my opinion, it’s not a time to be experimental, it’s a time to be conservative.
Why should refactoring be conservative? To answer that question, ask: what’s the point of refactoring at all? The point of refactoring is to make an investment in the code with the expectation that that investment will pay off. (Or, more precisely, that your refactoring investments in general will pay off on average.) Refactoring isn’t self-indulgent play. It’s serious business. We should only make changes to the code that we’re reasonably sure constitute an improvement. Once we’re no longer sure our changes are making the code better, we should stop refactoring—and maybe even do some reverting.
Of course, experimentation has its place. If we never experiment, we seriously limit our learning. One good way to experiment is with a spike: a small project which is intended from the beginning to be thrown away. I’m also not trying to say that refactorings should never ever contain experiments. Often they will. I’m just saying we should be conservative in our experimentation. Refactorings are bets. It’s okay to make risky bets sometimes. But we have to be conscious about our risk-taking or else too many of our bets will be losses.
Refactoring is one of those words that people throw around carelessly and abuse. Remember, if the change results in the behavior of the code changing, it’s not refactoring. And the point of refactoring is not to indulge one’s interest in fun new coding techniques. Refactoring is a business investment. A set of refactorings is a portfolio of investments. The more thoughtfully you make your investments, the better the chances that you’ll get a good return.