Modeling Values and Entities
In this pack:
sizing,
notation,
rule strictness.
Overview
Every domain concept is either a value or an entity, and the choice
decides how it behaves. A value is interchangeable with any other value
of the same contents, so it never changes and compares by those
contents. An entity is one thing with a history, so it carries an
identifier that never changes and compares by that identifier. This
skill makes the choice, turns ruled primitives into value types, and
keeps the two kinds from borrowing each other's rules.
When to use
- A new concept needs a type, and it is unclear whether two instances
with the same contents are the same thing.
- An identifier travels as a raw string or number, or two identifiers
of the same primitive type sit side by side.
- Editing one object changes another object that holds the same
instance.
- Two objects with equal contents compare unequal, or a set or a map
cannot find the one that is equal.
- The same format, range or unit check on a raw value appears in several
places.
- A concept has few fields, and someone argues it must therefore be a
value.
When not to use
- The type only carries data across a process or layer boundary, and no
rule depends on its equality. Keep it a plain data transfer object and
convert it at the edge. That is deciding object or data.
- The question is whether the type needs a class at all, or should stay
a record or a map. Decide that first with deciding object or data.
- The primitive has no rule of its own and one use, such as a free-text
note. Leave it as it is.
Core rules
Rule. Decide value or entity with one question: are two instances
with the same contents the same thing? If yes, it is a value: two
30-minute durations are interchangeable. If no, it is an entity: two
clinicians with the same surname are two clinicians, and a clinician
whose surname changes is still the same clinician.
Rule. Make a value immutable. An operation that would change it
returns a new value. A value can then be shared without a copy, and
no holder ever sees another holder's change.
Rule. Compare a value by all of its contents, and keep equality,
hashing and any ordering in agreement. Two equal values hash alike,
and an ordering ranks two values as equal exactly when they are
equal. In the notation value gives this equality; how a language
provides it belongs to the language packs.
Rule. Give an entity an identifier that is assigned once, when it
is created or first stored, and never changes. Compare two entities
by that identifier, never by their other attributes, which change
over the entity's life.
Default. Replace a primitive that carries a domain rule with a
value type. A raw string or number with a format, a range or a unit
repeats its check at every use, and two such parameters can be
swapped without an error. A value type checks the rule once, when it
is built, and turns the swap into a type error.
The exception is a primitive with no rule of its own and one use,
such as a free-text note: a type around it adds a name and protects
nothing.
Default. Put behaviour that needs only a value's contents on the
value. Adding two fees in one currency belongs to the fee.
The exception is an operation that needs a collaborator a value must
not hold, such as a currency rate service: keep it in a service that
takes the value.
Judgement. The same concept can be a value in one part of the
system and an entity in another; decide by what that part tracks. A
room is a value on an appointment letter and an entity for the team
that tracks its equipment and repairs.
Pattern
Before, Referral takes two strings and ReferralDesk.refer passes
them in the wrong order. Both parameters are String, so the swap
compiles and files the clinician as the patient.
Before:
class Referral
- patient: String
- clinician: String
+ new(patient: String, clinician: String)
class ReferralDesk
+ refer(patient: String, clinician: String): Referral
return new Referral(clinician, patient)
After, PatientId and ClinicianId are values. Each checks its format
once, in its constructor, and raises an error that names the broken
rule. text.hasPatientIdFormat() and text.hasClinicianIdFormat() are
taken to mean true when the text matches that identifier's format.
After:
value PatientId
- patientId: String
+ new(text: String)
raises MalformedPatientId
if text.hasPatientIdFormat() then
patientId := text
else
raise MalformedPatientId
value ClinicianId
- clinicianId: String
+ new(text: String)
raises MalformedClinicianId
if text.hasClinicianIdFormat() then
clinicianId := text
else
raise MalformedClinicianId
class Referral
- patient: PatientId
- clinician: ClinicianId
+ new(patient: PatientId, clinician: ClinicianId)
class ReferralDesk
+ refer(patient: PatientId, clinician: ClinicianId): Referral
return new Referral(patient, clinician)
Referral now takes the two types, so the old call,
new Referral(clinician, patient), is a type error: a ClinicianId is
not a PatientId. ReferralDesk.refer passes each identifier in its
own position. A factory would add nothing here, because each identifier
has one field and one way to be made.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A method that changes a field of an object that other objects also
hold.
- Two or more parameters of the same primitive type side by side, such
as two strings for two different identifiers.
- The same format or range check on a raw string or number in several
places.
- An entity compared by its name, phone number or other attributes that
change.
- A value type with a setter, or equality written without matching
hashing.
Common mistakes
- Making an entity a value because it has few fields: a patient with
only a name is still an entity.
- Wrapping every primitive, including ones with no rule and one use.
- Comparing entities by all their fields, so an edited copy no longer
equals the stored one.
- Using an attribute that can change as the identifier, such as a phone
number as the patient's key.
- Copying an immutable value defensively, which buys nothing.
Related skills
Further reading
- Equality and identity
- Immutable values
1---2name: oo-modeling-values-and-entities3description: Use when picking value or entity, when ids are raw strings or numbers, when editing one object changes another, or equal objects compare unequal.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-modeling-values-and-entities7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Modeling Values and Entities1213**In this pack:**14[sizing](../oo-design/SKILL.md#how-much-design-a-task-warrants),15[notation](../oo-design/references/notation.md),16[rule strictness](../oo-design/SKILL.md#how-strictly-a-rule-is-meant).1718## Overview1920Every domain concept is either a value or an entity, and the choice21decides how it behaves. A value is interchangeable with any other value22of the same contents, so it never changes and compares by those23contents. An entity is one thing with a history, so it carries an24identifier that never changes and compares by that identifier. This25skill makes the choice, turns ruled primitives into value types, and26keeps the two kinds from borrowing each other's rules.2728## When to use2930- A new concept needs a type, and it is unclear whether two instances31 with the same contents are the same thing.32- An identifier travels as a raw string or number, or two identifiers33 of the same primitive type sit side by side.34- Editing one object changes another object that holds the same35 instance.36- Two objects with equal contents compare unequal, or a set or a map37 cannot find the one that is equal.38- The same format, range or unit check on a raw value appears in several39 places.40- A concept has few fields, and someone argues it must therefore be a41 value.4243## When not to use4445- The type only carries data across a process or layer boundary, and no46 rule depends on its equality. Keep it a plain data transfer object and47 convert it at the edge. That is deciding object or data.48- The question is whether the type needs a class at all, or should stay49 a record or a map. Decide that first with deciding object or data.50- The primitive has no rule of its own and one use, such as a free-text51 note. Leave it as it is.5253## Core rules54551. Rule. **Decide value or entity with one question: are two instances56 with the same contents the same thing?** If yes, it is a value: two57 30-minute durations are interchangeable. If no, it is an entity: two58 clinicians with the same surname are two clinicians, and a clinician59 whose surname changes is still the same clinician.60612. Rule. **Make a value immutable.** An operation that would change it62 returns a new value. A value can then be shared without a copy, and63 no holder ever sees another holder's change.64653. Rule. **Compare a value by all of its contents, and keep equality,66 hashing and any ordering in agreement.** Two equal values hash alike,67 and an ordering ranks two values as equal exactly when they are68 equal. In the notation `value` gives this equality; how a language69 provides it belongs to the language packs.70714. Rule. **Give an entity an identifier that is assigned once, when it72 is created or first stored, and never changes.** Compare two entities73 by that identifier, never by their other attributes, which change74 over the entity's life.75765. Default. **Replace a primitive that carries a domain rule with a77 value type.** A raw string or number with a format, a range or a unit78 repeats its check at every use, and two such parameters can be79 swapped without an error. A value type checks the rule once, when it80 is built, and turns the swap into a type error.8182 The exception is a primitive with no rule of its own and one use,83 such as a free-text note: a type around it adds a name and protects84 nothing.85866. Default. **Put behaviour that needs only a value's contents on the87 value.** Adding two fees in one currency belongs to the fee.8889 The exception is an operation that needs a collaborator a value must90 not hold, such as a currency rate service: keep it in a service that91 takes the value.92937. Judgement. **The same concept can be a value in one part of the94 system and an entity in another; decide by what that part tracks.** A95 room is a value on an appointment letter and an entity for the team96 that tracks its equipment and repairs.9798## Pattern99100Before, `Referral` takes two strings and `ReferralDesk.refer` passes101them in the wrong order. Both parameters are `String`, so the swap102compiles and files the clinician as the patient.103104Before:105106```text107class Referral108 - patient: String109 - clinician: String110 + new(patient: String, clinician: String)111112class ReferralDesk113 + refer(patient: String, clinician: String): Referral114 return new Referral(clinician, patient)115```116117After, `PatientId` and `ClinicianId` are values. Each checks its format118once, in its constructor, and raises an error that names the broken119rule. `text.hasPatientIdFormat()` and `text.hasClinicianIdFormat()` are120taken to mean true when the text matches that identifier's format.121122After:123124```text125value PatientId126 - patientId: String127 + new(text: String)128 raises MalformedPatientId129 if text.hasPatientIdFormat() then130 patientId := text131 else132 raise MalformedPatientId133134value ClinicianId135 - clinicianId: String136 + new(text: String)137 raises MalformedClinicianId138 if text.hasClinicianIdFormat() then139 clinicianId := text140 else141 raise MalformedClinicianId142143class Referral144 - patient: PatientId145 - clinician: ClinicianId146 + new(patient: PatientId, clinician: ClinicianId)147148class ReferralDesk149 + refer(patient: PatientId, clinician: ClinicianId): Referral150 return new Referral(patient, clinician)151```152153`Referral` now takes the two types, so the old call,154`new Referral(clinician, patient)`, is a type error: a `ClinicianId` is155not a `PatientId`. `ReferralDesk.refer` passes each identifier in its156own position. A factory would add nothing here, because each identifier157has one field and one way to be made.158159## Red flags160161Places to look, not verdicts. A red flag becomes a finding only with162evidence: a measurement, a reproducible bug, or a failing test.163164- A method that changes a field of an object that other objects also165 hold.166- Two or more parameters of the same primitive type side by side, such167 as two strings for two different identifiers.168- The same format or range check on a raw string or number in several169 places.170- An entity compared by its name, phone number or other attributes that171 change.172- A value type with a setter, or equality written without matching173 hashing.174175## Common mistakes176177- Making an entity a value because it has few fields: a patient with178 only a name is still an entity.179- Wrapping every primitive, including ones with no rule and one use.180- Comparing entities by all their fields, so an edited copy no longer181 equals the stored one.182- Using an attribute that can change as the identifier, such as a phone183 number as the patient's key.184- Copying an immutable value defensively, which buys nothing.185186## Related skills187188- [oo-design](../oo-design/SKILL.md) sizes the task and defines the189 rule labels.190- [oo-deciding-object-or-data](../oo-deciding-object-or-data/SKILL.md)191 decides whether a concept needs a class at all, before this skill192 picks a value or an entity.193- [oo-constructing-valid-objects](../oo-constructing-valid-objects/SKILL.md)194 builds an identifier with one constructor that rejects malformed text.195- [oo-encapsulating-state-and-behaviour](../oo-encapsulating-state-and-behaviour/SKILL.md)196 keeps an entity's state behind messages and says when a mutable value197 crosses a boundary as a copy.198199## Further reading200201- [Equality and identity](references/equality-and-identity.md)202- [Immutable values](references/immutable-values.md)