exercises and solutions
Refactoring exercises
Refactoring exercises improve structure without changing behaviour. Start with a small code smell, preserve the current result with a check, make one focused change, and rerun the check.
Example Review Sequence
1. Capture the current output with a test or runnable example.
2. Identify one responsibility to extract or one name to clarify.
3. Change the smallest useful surface.
4. Run the same checks.
5. Explain why behaviour stayed the same.
Useful tasks include replacing duplicated validation, extracting a calculation from a controller, introducing a value object, or separating SQL from HTML rendering. Avoid broad rewrites where the learner cannot prove what stayed stable.
Practice
Extract A Calculation From A Controller
Describe how to move basket-total arithmetic out of a controller while proving that behaviour stays the same. Name the check you would add before refactoring.
Show solution
Capture normal, empty, and invalid-quantity behaviour with focused checks. Move the arithmetic into a named function or domain object, keep request handling in the controller, and rerun the same checks.
The refactor is successful when responsibilities are clearer and externally observable behaviour is unchanged.
Replace Duplicated Validation
Two request handlers independently trim and validate the same email field. Describe a small refactor that removes duplication without hiding the validation rules.
Show solution
Capture normal, empty, and invalid-email cases first. Extract a small named validator or value object that trims, validates, and returns the accepted value or a clear failure. Update one handler, rerun checks, then update the second.
Keep rendering and HTTP response decisions in the handlers. The shared component should own only the repeated validation rule.