Refactoring Remove Setting Method
ProblemThe value of a field should be set only when it is created, and not change at any time after that.
SolutionSo remove methods that set the field's value.
You want to prevent any changes to the value of a field.
How to Refactor
The value of a field should be changeable only in the constructor. If the constructor does not contain a parameter for setting the value, add one.
Find all setter calls.
- If a setter call is located right after a call for the constructor of the current class, move its argument to the constructor call and remove the setter.
- Replace setter calls in the constructor with direct access to the field.
- Delete the setter.
Tired of reading?
No wonder, there are 7 hours worth of the text on this website.
Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.Learn more...
Everything is quite simple. This example is like video (but much cooler):
- After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
- You can fast-forward or return to previous steps by pressing arrow buttons on the left.
- Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
- To check the code for errors, you can press "Compile and test" button ()