Kent Beck once said:
Make the change easy, then make the easy change.
This is a very concise way of saying that you have to maintain and update your code’s design.
The long-term success of a software product depends largely on its design – on the shape of the code.
Designs that are unhelpful resist change. If you want to add a new feature and that addition is easy, then the design is suited to accepting that new feature. However, if you want to add a feature and that addition is hard, the design is not suited to naturally accept that feature.
As shorthand, we call software that is organized so that change is almost always hard “bad code”.
But that doesn’t mean we can be complacent when we have good code. Nor does it mean code that resists one particular change is automatically bad.
To really be successful, you need to keep the design clean. You can’t predict what changes you will need to make, so you will sometimes need to alter your design to support a new feature.
The best way to accomplish this is to change the design first and then add the new functionality. In other words, before you even attempt to add the functionality, you need to change the design so that it will naturally support the functionality, and only then do you add the new functionality.
This process is beneficial for a number of reasons:
- It guarantees that designs stay up to date
- It discourages kludgy workarounds
- It is actually cheaper than just trying to “hack it in”
- It prevents decay in your codebase
An implication of this fact is that, when you are preparing code to accept a new feature that its design can’t currently accommodate, you really should only change design.
That’s What Tests Are For, Right?
Often, when I bring this up with someone who has a disciplined view of what software professionalism looks like, their response is “That’s what TDD is for!”
Tests are great. I love TDD. Nothing in this post, or any other of my writings, should be construed as a disparagement of tests. In fact, I think we should have this as one of our highest rules:
A well-designed and maintained test suite being necessary to the freedom of a codebase, the right to build and execute tests shall not be infringed.
That said, if you think tests help you with the problem of needing to update design, I’ve got bad news for you: The help they provide is limited at best.
For one thing, there is no guarantee that your test suite covers every behavior in your system. We try to write tests for every behavior – especially for every behavior that matters to a stakeholder – but there is no way to be sure.
For another, not all code is testable in its present form. Legacy code comes to mind, and there is a vast amount of it serving as a foundation for our modern economy. Code that connects to external systems — APIs, queues, payment gateways — is another example of code that isn’t practical to test directly. And, of course, tests themselves can’t be tested in any meaningful way.
In the dream, every behavior in a codebase is specified by exactly one test. When you awaken to the harsh reality of your circumstances, this is simply not the case and likely never will be.
So if tests can’t guarantee safety, how do we know we’re truly refactoring? I’ll come back to that in toward the end.
The Word “Refactoring” and Its Very Specific Meaning
Many use the word “refactoring” to mean simply “changing design”. That, however, is not what it means at all. One could argue that “just changing design” is more or less what the book Refactoring was arguing against.
Refactoring, specifically, means changing design without changing behavior.
This does not mean that some of the changes didn’t change behavior. To be considered refactoring, all of the changes in a sequence must preserve behavior.
It doesn’t mean that changes mostly preserve behavior. To be refactoring, each step must have literally no impact on function.
Most importantly: It doesn’t mean you’re “pretty sure” or “hoping” that behavior was preserved. If you’re not completely confident, it wasn’t refactoring.
Refactoring is a highly-disciplined approach to changing design that manifests zero tolerance for altering functionality.
“But How?”
When I finally get through to someone and help them see what it really is, the response is often incredulity.
“Sure. [The real] definition of refactoring would be great,” they say, “if it were possible.”
I assure you: It is possible, and a focus on continuity is the key.
Refactoring – true refactoring – is a deeply disciplined and rigorous approach to changing design.
It is founded on small, provably transformative operations. Each operation is something that you, and any developer who is watching, can easily prove with math does not modify behavior.
Imagine adding a new local variable to a method. You’re not modifying any existing methods. You’re not changing how a method is used. You’re not forcing that method to be used. It has a unique name within the method.
You know that won’t change behavior. Yet it observably has changed design.
Such tiny changes are so small that they can safely be considered smooth transformational acts applied to the design – as if you’re molding a lump of clay.
Any reliable automation and any manual step that is provably transformative can be considered an “atom” of refactoring.
“But How?”
From these atoms of refactoring one can build larger structures.
Continuing the chemistry analogy, we might think of larger operations like emerging a class from the local variables in an algorithm as “molecules”.
Then we can assemble those operations into still larger operations, such as transforming a type code field into a polymorphic hierarchy. This is where the chemistry analogy starts to lose its effectiveness. Chemistry has larger structures, but their names aren’t widely known. The point is that they’re just bigger arrangements in the same space.
It is recursively macrocosmic in this way. You can build higher and higher levels of refactoring operations, each out of lower-order sequences.
The reason this is possible is one of the worst-advertised facts in software development.
Consider some design A. Now imagine a change that moves your software from design A to A'. If you know for a fact that this step does not change behavior, then you know that A == A'. Now, if we consider another change that moves from A' to A'' and makes the same guarantee, that means we know that A' == A''.
The transitive property is then what makes this all work and ultimately tells us that the entire sequence was provably transformative: A == A''.
This means that you know that the larger operation comprising the two smaller ones, so you can apply the exact same reasoning to two such larger operations.
For example, consider the following progression:
if (X >= 1) F();
if (X - 1 >= 1 - 1) F();
if (X - 1 >= 0) F();
Each of those steps is provably the same behavior as its predecessor and, therefore, we know that if (X >= 1) is the same as if (X - 1 >= 0). You can then assembly that step into even larger steps that you have proven are safe, like if (X >= 1) → if (X > 0) (for integers).
If you know these practices and techniques, you can literally transform a legacy code system with procedural (if you’re lucky!) logic embedded directly in GUI code into something that can easily be tested, changed, and understood. You can spend days gradually transforming the design in this way and never have a reason to worry that you might have broken something.
Why it Matters
When I was in the Boy Scouts, I was taught – and then learned in a very practical way – that small things can cause great harm. Common examples when hiking in the woods are hotspots, which turn to blisters and the sores, and pebbles or debris in your boots, which can cut and cause infections.
The principle which underlies this also applies to changing design and it’s why true refactoring is so very important.
All large changes are really strings of smaller changes.
When you apply true refactoring, you can manage these changes and use them to elegantly emerge any design structure you need, even from seemingly chaotic spaghetti code.
If, however, you allow even one small modification of behavior into your sequence, then every change after that has the potential to impact functionality in unforeseen ways. An ostensibly small change that seemed innocuous, at first, can fester into something truly catastrophic.
For this reason, refactoring must have zero tolerance for the admission of changes to behavior. For the reasons already outlined earlier, the only workable method for ensuring that function remains unchanged is to ensure that each atomic step in a refactoring operation is provably transformative.
A New Standard for Refactoring
That brings us back to the practical question: how do you know if you’re refactoring?
Here’s the standard I propose: Your measure of true refactoring is the time from random interruption to demo-ability.
I’ll explain more in a few paragraphs. First, I’ll need to give you some context.
I train with pistols, among other things. One of the things you practice in this kind of training is the timing of your draw. To do this training, we use a device called a “shot timer”.
It can be configured to beep at a random time (e.g., sometime between 1 and 5 seconds from now), and it records the time to your first shots and the increments (“splits”) to subsequent shots.
This, at once, provides a training mechanism (the random buzzer to initiate action) and an optimization mechanism (telling you how long it takes to start and complete a pattern).
I propose that you use a similar mechanism to augment your refactoring skills. When you start making changes to a system, set a timer to go off some random amount of time between a floor and a ceiling. For instance “between 5 and 15 minutes from now”.
When that timer goes off, immediately stop changing the system and start trying to return the system into a demo-able state.
If you were truly refactoring, all your changes were smooth, small, and provably transformative. Notwithstanding things like compile time, you should be able to more or less immediately demonstrate that the system works the same way it did before you started altering design.
If, on the other hand, you have to do a bunch of work to get something to compile, or spend time hunting down and finishing changes, you can be pretty sure that whatever you were doing was not refactoring.
Just as a shot timer measures a marksman’s readiness under pressure, this timer will measure your readiness as a refactorer. Both demand discipline, zero hesitation, and zero tolerance for sloppiness.
Use this method once a week. Track your “draw time” and drive it down. I guarantee it will make you better at refactoring and a better developer.
I recommend giving our Refactoring Shot Timer a try with this approach.