This question has kicked around a bit at Thoughtworks lately, sparked by this article:
I thought I’d blog what I do, since a few bits of feedback lead me to believe I might be good at it.
I don’t refactor when…
…I spend five minutes on it and realise I’m not getting anywhere. I can always think about a more incremental approach and come back to it later.
…I don’t understand the benefit that the code provides. Sometimes it turns out that it doesn’t provide any; I usually double-check that assumption before I delete the code. I might talk to the person who wrote the code to get their ideas.
…I am technically ignorant. I might give it a go, especially if my pair knows how to help – it’s an opportunity for me to learn something new – but I’ll usually timebox it, and revert if I take too long.
…I’m under pressure of time to get something done… but it’ll be on my todo list, and I won’t ask permission to finish it off properly once the pressure’s less (and if you don’t like that, give me another reason not to do it).
…it’s hard, and I don’t need to. If it’s someone else’s code and no one’s using it, reading it or changing it, the time saved won’t pay itself back any time soon. If it’s my code, it got that way because it’s built on top of someone else’s, and I need to sort that out first. This is how tech debt arises. If it turns out that it’s holding us back, and it’s time to pay for it, then I might volunteer to be part of that pair.
…someone absolutely forbids me from doing it, notwithstanding the above. Anyone doing this is letting themselves in for my ‘told you so’ when it comes back to bite. If it’s going to take less than an hour, you might as well let me go ahead and do it anyway – we’ll spend half an hour arguing, and (even though I no longer sulk about it) I’m far less productive when you kill my spontenaiety.
I do refactor when…
…it doesn’t fall into one of the above. This includes easy refactorings that I don’t need to make. If I’ve seen it, something must have sent me there! That means the chances of someone else reading it are reasonable.
I should mention that I’ve never been forbidden from refactoring anything. I’ve seen it happen once. Two pairs both tried to use the resulting mess. The refactoring would have taken one pair two hours; the mess caused each of two pairs a full day. There were definitely some ‘told you so’ moments, which is why I think the arguments are worthwhile.
I have, in the past, made huge and significant mistakes while trying to refactor! This learning experience has helped me become better at it. Everyone should have that opportunity.
Nowadays, I rarely ask permission. I justify my time by the time it’s likely to save in the future – whether in related code, similar code or simply because people (including me) are learning from good habits. If I can’t justify the time, I don’t refactor!