Skip to content

Refactoring

gesellc edited this page Aug 25, 2016 · 9 revisions

What it is...

Improve the code without changing its functionality.

References

Refactoring is a whole discipline in itself, and it even has a reference book: Martin Fowler’s Refactoring.

Refactoring Sound Bites

"When refactoring, work on either the code or the tests, but not both at once."

Refactoring Techniques

This is a running list, copied and interpreted from our text book.

Eliminate Duplication

So what do we do during the Refactor stage? What justifies moving from an implementation where we "cheat" to one we’re happy with?

One methodology is eliminate duplication: if your test uses a magic constant (like the "1:" in front of our list item), and your application code also uses it, that counts as duplication, so it justifies refactoring. Removing the magic constant from the application code usually means you have to stop cheating.

source: Percival

Triangulation

I find that leaves things a little too vague, so I usually like to use a second technique, which is called triangulation: if your tests let you get away with writing "cheating" code that you’re not happy with, like returning a magic constant, write another test that forces you to write some better code. That’s what we’re doing when we extend the FT to check that we get a "2:" when inputting a second list item.

source: Percival

Three Strikes and Refactor - The moment to DRY

There’s a principle called don’t repeat yourself (DRY), which we like to apply by following the mantra three strikes and refactor. You can copy and paste code once, and it may be premature to try and remove the duplication it causes, but once you get three occurrences, it’s time to remove duplication.

source: Percival

Tips on Refactoring

Don’t forget the "Refactor" in "Red, Green, Refactor"

The whole point of having tests is to allow you to refactor your code! Use them, and make your code as clean as you can.

Don’t refactor against failing tests

In general!

But the FT you’re currently working on doesn’t count.

You can occasionally put a skip on a test which is testing something you haven’t written yet.

More commonly, make a note of the refactor you want to do, finish what you’re working on, and do the refactor a little later, when you’re back to a working state.

Don’t forget to remove any skips before you commit your code! You should always review your diffs line by line to catch things like this.

Clone this wiki locally