Many low-level tools can be deployed when refactoring; here are 8 fantastic tactics we saw groups using at the Refactoring Workshop we held at Ruby Hack Night
- Use your tests. Never make more changes before testing than you can debug and revert without pain. Some groups made a lot of small changes before testing, and then wasted time trying to figure out change had the typo. Testing saves time in the long run.
- When you have tests, experiment. Hack and slash. Delete code and see what breaks. It’s faster to check the effects in the characterization diff than to tortuously map the logic.
- Repeat yourself. Any code worth refactoring is hard to understand, and explicitly adding stuff back in that had been extracted will make it easier to understand. Then you can pull it out again.
- Use only one name for a thing, and use it only for that thing. Once you start conflating ‘value’ and ‘quality’, confusion reigns.
- If you don’t know where to start, try refactoring the code to follow Ruby idioms (or the idioms of whichever language you’re using). By clearing out the deadwood, and the obvious, distracting problems, you’ll make it easier to identify more serious issues.
- Invert negative checks:
‘foo != bar’
statements indicate code needing refactoring. Positive tests are much easier to read and understand, so inverting those negative tests is a good way to clarify the code’s structure. - Extracting checks to separate methods: Gilded Rose is littered with checks. Extracting those checks from the main body of the code and turning them into methods provides two benefits: a) It vastly reduces visual clutter, making the code easier to read; b) By giving the check methods good, descriptive names, the code becomes much more expressive. “if stale? item” contains much more meaning than “if item.sell_in < 0”.
- Try refactoring code into sub-methods even before you know what they do. By isolating them visually, you’ll have an easier time picking them apart.
If you have any stories you’d like to add about how you used these tactics, or if there are tools you think should be added to the list, drop a comment!
Next up: larger scale refactoring strategies, and a more in-depth look at some of these tactics.
[Click for more articles from our Development series]
[Click for more articles from our Workshop series]
[Click to learn more about Ryatta]