Special Cases: When to Allow Mutability
Immutability is a great simplifier in an implementation, making sharing and reference
passing safe. It is also consistent with the meaning of a value. If the value of an
attribute changes, you use a different
VALUE OBJECT
, rather than modifying the existing
one. Even so, there are cases when performance considerations will favor allowing a
VALUE OBJECT
to be mutable. These factors would weigh in favor of a mutable
implementation:
If the
VALUE
changes frequently
If object creation or deletion is expensive
If replacement (rather than modification) will disturb clustering (as discussed in
the previous example)
If there is not much sharing of
VALUES
, or if such sharing is forgone to improve
clustering or for some other technical reason
Just to reiterate: If a
VALUE
's implementation is to be mutable, then it
must not
be
shared. Whether you will be sharing or not, design
VALUE OBJECTS
as immutable when
you can.
Defining
VALUE OBJECTS
and designating them as immutable is a case of following a general rule:
Avoiding unnecessary constraints in a model leaves developers free to do purely technical
performance tuning. Explicitly defining the essential constraints lets developers tweak the design
while keeping safe from changing meaningful behavior. Such design tweaks are often very specific
to the technology in use on a particular project.
Example
Tuning a Database with V
ALUE
O
BJECTS
Databases, at the lowest level, have to place data in a physical location on a disk, and it takes
time for physical parts to move around and read that data. Sophisticated databases attempt to
cluster these physical addresses so that related data can be fetched from the disk in a single
physical operation.
If an object is referenced by many other objects, some of those objects will not be located nearby
(on the same page), requiring an additional physical operation to get the data. By making a copy,
rather than sharing a reference to the same instance, a
VALUE OBJECT
that is acting as an attribute
of many
ENTITIES
can be stored on the same page as each
ENTITY
that uses it. This technique of
storing multiple copies of the same data is called
denormalization
and is often used when access
time is more critical than storage space or simplicity of maintenance.
In a relational database, you might want to put a particular
VALUE
in the table of the
ENTITY
that
owns it, rather than creating an association to a separate table. In a distributed system, holding a
reference to a
VALUE OBJECT
on another server will probably make for slow responses to messages;
instead, a copy of the whole object should be passed to the other server. We can freely make
these copies because we are dealing with
VALUE OBJECTS
.
Do'stlaringiz bilan baham: |