Also known as

Refactoring Remove Setting Method

Problem

The value of a field should be set only when it is created, and not change at any time after that.

Solution

So remove methods that set the field's value.
Before
Remove Setting Method - Before
After
Remove Setting Method - After

Why Refactor

You want to prevent any changes to the value of a field.

How to Refactor

  1. 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.

  2. 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.
  1. 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...

Live Example

First time here? No worries!

Everything is quite simple. This example is like video (but much cooler):

  1. After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
  2. You can fast-forward or return to previous steps by pressing arrow buttons on the left.
  3. Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
  4. To check the code for errors, you can press "Compile and test" button ()