Change Reference to Value.
You have a reference object that’s too small and infrequently changed to justify managing its life cycle.
Turn it into a value object.
##Example
class Currency {
private String code;
// one shared instance per code, compared with ==
}class Currency {
private final String code;
Currency(String code) {
this.code = code;
}
@Override
public boolean equals(Object other) {
return other instanceof Currency
&& code.equals(((Currency) other).code);
}
@Override
public int hashCode() {
return code.hashCode();
}
}##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.
##How to Refactor
-
Make the object unchangeable. The object shouldn’t 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.
-
Create a comparison method to be able to compare two values.
-
Check whether you can delete the factory method and make the object constructor public.