Refactoring Patterns
Learning Goals
- Explain how refactoring fits into the RED-GREEN-REFACTOR cycle
- Identify the difference between refactoring and “changing stuff”
- Define and apply the Move Method refactoring pattern
- Define and apply the Extract Class refactoring pattern
- Define and apply the Hide Delegate refactoring pattern
Slides
Available here
Warmup
- Why do we refactor?
- What’s the difference between “refactoring” and “changing stuff”?
- Does refactoring always make code better?
Key Points
“What if we move it over here… will that fix it?”
Let’s start by discussing Refactoring at a high level:
-
The “Red-Green-Refactor” loop
- Red - Create a unit test that fails.
- Green - Write code to make the unit test pass.
- Refactor - Clean up the messiness.
- Changing the internals of code without changing the external behavior
- The concept of technical debt and awkward analogies to personal debt
- Software patterns are common solutions to common problems
- Refactoring patterns are common transformations, not improvements .
-
Three common refactoring patterns
- Move Method
- Where should it live?
- What is the role of the class, does this functionality belong?
- Which class/object does this method reference?
- Extract Class
- Can you make chunks of methods?
- Can they be grouped to feel like an object?
- Would they have attributes?
- Sandi Metz rules: Class should be less than 100 lines
- Hide Delegate
- What does the interface look like? Can we simplify it?
- Law of Demeter
- Protect from change
- Move Method
Live Refactoring
For the next two hours you will apply the three refactoring patterns outlined above to this repository. Spend forty minutes on each.
WrapUp
- What was challenging about refactoring the above exercises?
- Which refactoring pattern might you reach for first?
- Explain each refactoring pattern and the key motivation for using it.
Homework
- Tonight you should watch Katrina’s Therapeutic Refactoring talk.
Additional Resources
- The readings we used today can be found here. Read through the refactoring patterns not covered in this lesson.