Refactoring is the new documentation
Much has been written about the subject of refactoring code over the years including some very well known work by Martin Fowler. There are many resources on the ‘what’ and ‘how’ of refactoring out on the web so I don’t intend to go back over those aspects of the topic here other than to mention that if you’re new to the concept, refactoring is essentially improving the internal design of software without changing its external behaviour.
One thing that’s traditionally been difficult to explain or understand though, and remains that way, is the question of ‘why to refactor’. Putting work into something without changing what it does can seem like it’s going to be a big load of wasted effort. At best, it often looks like a speculative investment of time with intangible payback. Experience shows though that refactoring can pay big dividends, avoid wasted effort and create consistent direction, focus and efficiency on a project.
Martin Fowler writes that refactoring makes changing software easier in the future. That’s very true but to those new to the concept (or non-programmers) it can still be difficult to explain how that happens. It sounds a little bit ‘magic’.
For me it simply comes down to this though. Writing code isn’t only about solving a problem. It’s also about describing the solution. Really great code not only functions well but explains to other programmers what the problem was that caused the code to be written and how it was solved. That’s where the ease of change comes in. In contrast, if code is incomprehensible, often the reasons behind it aren’t fully understood when changes are needed. That tends to encourage either starting again (wasted effort), large amounts of careful tracing through the code, or unintentional breaking of parts of the system when changes are made without fully understanding their impact.
Of course, you can write comments and supplementary documentation around code and they both have their place. Documentation can easily get out of step with code without extreme care though and it’s difficult to test completeness or accuracy of the written word. Well written code doesn’t have that problem. The documentation can’t get out of step with the implementation because the implementation is the documentation.
Of course, pragmatism and business forces do count in the real world and sometimes refactoring isn’t justified, for instance on a soon to retire system. Often though, taking working code and making changes which help to teach the current and future teams about the nature of the problem it solves is well worth the effort. And just like other forms of documentation, refactoring is worth doing before the original learning and knowledge gained by the very process of creating the solution is lost and has to be re-learnt all over again. Used wisely, refactoring’s a valuable investment in team knowledge and ongoing clarity of thinking.