Refactoring Change Reference to Value

Problem

You have a reference object that is too small and infrequently changed to justify managing its life cycle.

Solution

Turn it into a value object.
Before
Change Reference to Value - Before
After
Change Reference to Value - After

Why Refactor

Inspiration to switch from a reference to a value may come from the inconvenience of working with the reference. References require management on your part:

  • They always require requesting the necessary object from storage.
  • References in memory may be inconvenient to work with.
  • Working with references is particularly difficult, compared to values, on distributed and parallel systems.

Values are especially useful if you would rather have unchangeable objects than objects whose state may change during their lifetime.

Benefits

  • One important property of objects is that they should be unchangeable. The same result should be received for each query that returns an object value. If this is true, no problems arise if there are many objects representing the same thing.

  • Values are much easier to implement.

Drawbacks

  • If a value is changeable, make sure if any object changes that the values in all the other objects representing the same entity are updated. This is so burdensome that it is easier to create a reference for this purpose.

How to Refactor

  1. Make the object unchangeable. The object should not have any setters or other methods that change its state and data (Remove Setting Method may help here). The only place where data should be assigned to the fields of a value object is a constructor.

  2. Create a comparison method to be able to compare two values.

  3. Check whether you can delete the factory method and make the object constructor public.

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 ()