Refactor without changing behaviour
- Skill
- Refactoring with AI
- Time
- About 35 min
- Access
- Full track
This function prints shipping labels. It works, it’s been in production for years, and everyone is scared to touch it. You’ve been asked to make it readable so the team can add a new country next sprint.
The rule of a refactor: behaviour stays exactly the same, including the odd parts. AI assistants love to “improve” code while refactoring, and quietly change what it does.
Do this
- Before touching the code, write tests that pin down its current behaviour (characterisation tests). Include the strange inputs, not just the normal ones.
- Refactor it, with AI if you like.
- Run the same tests against the new version.
Submit
- Your refactored function
- Your characterisation tests
- Anything in the old behaviour that surprised you, and whether you kept it
shipping-label.js
// shipping-label.jsfunction getShippingLabel(o) { var r = ''; if (o) { if (o.address) { if (o.address.country == 'US') { r = o.name + '\n' + o.address.line1 + '\n' + (o.address.line2 ? o.address.line2 + '\n' : '') + o.address.city + ', ' + o.address.state + ' ' + o.address.zip; } else { if (o.address.country == 'GB') { r = o.name.toUpperCase() + '\n' + o.address.line1 + '\n' + (o.address.line2 ? o.address.line2 + '\n' : '') + o.address.city.toUpperCase() + '\n' + o.address.zip.toUpperCase(); } else { r = o.name + '\n' + o.address.line1 + '\n' + (o.address.line2 ? o.address.line2 + '\n' : '') + o.address.zip + ' ' + o.address.city + '\n' + o.address.country; } } if (o.express == true) { r = '*** EXPRESS ***\n' + r; } } else { r = 'NO ADDRESS'; } } else { r = 'NO ADDRESS'; } return r;} module.exports = { getShippingLabel };This task is in the full track
You can read the brief above. To submit it, unlock all 10 tasks for $9, once. Unlimited resubmissions, and a full refund within 7 days if it isn’t useful.
Create a free account to get your review
Your answer stays here. Reviews are saved to your account so you can come back to them.
or with email
Already have an account?