Patterncore
Value object
Also called Value Object, value type object.
A value object is a small object, such as an amount of money or a date range, that is equal to another when their values are equal. It is usually immutable.
- Family
- architectural
- Intent
- Make a small object whose equality depends on its values and not on its identity.
Intent
A value object is "A small simple object, like money or a date range, whose equality isn't based on identity."1 Two value objects with the same values are equal, also when they are two different objects in memory. Usually, a value object cannot change after it is created.
Problem
Programs use many small compound values: a point, an amount of money, a range of dates, an email address. The program must decide when two of these are the same. Fowler writes: "Objects that are equal due to the value of their properties, in this case their x and y coordinates, are called value objects."2
Many languages compare objects by identity by default. Then two date ranges from March 1 to March 10 are not equal, and a map with one of them as a key does not find the other. If the objects can change, there is a second problem: two parts of the program can share one object, and a change in one part also changes the other.
Solution
Make the small value a class of its own, and give it the behavior of a value. The parts are:
- Fields that are the value. The fields together are the value, and the object has no other identity.
- Equality from the fields. Two objects are equal when all their fields are equal. The hash, if the language has one, also comes from the fields, so the object can be a key in a map.
- No change after creation. The bliki says: "To avoid aliasing bugs I follow a simple but important rule: value objects should be immutable".2 An operation that changes the value returns a new object.
- Checks in the constructor. The constructor rejects values that are not valid, such as a date range with its end before its start, so each object that exists is valid.
- Behavior. The class has the operations of the value, such as
containsfor a date range. Fowler suggests a Range class to prevent "duplicate fiddling with start and end attributes".2
a = DateRange(Mar 1, Mar 10) b = DateRange(Mar 1, Mar 10)
a == b -> true (equal fields)
a is b -> false (two objects)
a.extend_to(Mar 15) -> a new DateRange; a does not change
Many languages make such a class with little code. In Python, "If eq and frozen are both true, by default @dataclass will generate a hash() method for you."3 With frozen, "assigning to fields will generate an exception."3
from dataclasses import FrozenInstanceError, dataclass, replace
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(2, 3)
print("equal by value:", p == Point(2, 3))
print("usable as a set member:", p in {Point(2, 3)})
try:
p.x = 5
except FrozenInstanceError:
print("p cannot change")
print("a changed copy:", replace(p, x=5))
equal by value: True
usable as a set member: True
p cannot change
a changed copy: Point(x=5, y=3)
Example
Each example has a DateRange value object with a start day and an end day. The program makes two equal ranges a and b, and shows that they are equal but are not the same object. It extends a to March 15, which gives a new range c and does not change a. It puts a as a key in a map and finds the entry with b. Last, it tries to make a range with its end before its start, and the constructor rejects it.
from dataclasses import dataclass, replace
from datetime import date
@dataclass(frozen=True) # equality and hash by the fields; no assignment after creation
class DateRange:
start: date
end: date
def __post_init__(self):
if self.end < self.start:
raise ValueError("the end is before the start")
def contains(self, day):
return self.start <= day <= self.end
def extend_to(self, end):
return replace(self, end=end) # a new value; self does not change
def __str__(self):
return f"{self.start}..{self.end}"
def yn(b):
return "yes" if b else "no"
a = DateRange(date(2026, 3, 1), date(2026, 3, 10))
b = DateRange(date(2026, 3, 1), date(2026, 3, 10))
print("a equals b:", yn(a == b))
print("a and b are the same object:", yn(a is b))
c = a.extend_to(date(2026, 3, 15))
print("a:", a)
print("c:", c)
rooms = {a: "room 4"}
print("the room for b:", rooms[b])
print("a contains 2026-03-05:", yn(a.contains(date(2026, 3, 5))))
print("a contains 2026-03-12:", yn(a.contains(date(2026, 3, 12))))
try:
DateRange(date(2026, 3, 10), date(2026, 3, 1))
except ValueError as e:
print("error:", e)
a equals b: yes
a and b are the same object: no
a: 2026-03-01..2026-03-10
c: 2026-03-01..2026-03-15
the room for b: room 4
a contains 2026-03-05: yes
a contains 2026-03-12: no
error: the end is before the start
- Verdict: stdlib.
@dataclass(frozen=True)generates__eq__and__hash__from the fields, and an assignment to a field raisesFrozenInstanceError.dataclasses.replacemakes a changed copy. __post_init__checks the rule of the value, so noDateRangecan have its end before its start.
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
public class Main {
// A record gets equals, hashCode and toString from its components, and its fields are final.
record DateRange(LocalDate start, LocalDate end) {
DateRange {
if (end.isBefore(start)) throw new IllegalArgumentException("the end is before the start");
}
boolean contains(LocalDate day) {
return !day.isBefore(start) && !day.isAfter(end);
}
DateRange extendTo(LocalDate newEnd) {
return new DateRange(start, newEnd); // a new value; this does not change
}
@Override
public String toString() {
return start + ".." + end;
}
}
static String yn(boolean b) { return b ? "yes" : "no"; }
public static void main(String[] args) {
DateRange a = new DateRange(LocalDate.of(2026, 3, 1), LocalDate.of(2026, 3, 10));
DateRange b = new DateRange(LocalDate.of(2026, 3, 1), LocalDate.of(2026, 3, 10));
System.out.println("a equals b: " + yn(a.equals(b)));
System.out.println("a and b are the same object: " + yn(a == b));
DateRange c = a.extendTo(LocalDate.of(2026, 3, 15));
System.out.println("a: " + a);
System.out.println("c: " + c);
Map<DateRange, String> rooms = new HashMap<>();
rooms.put(a, "room 4");
System.out.println("the room for b: " + rooms.get(b));
System.out.println("a contains 2026-03-05: " + yn(a.contains(LocalDate.of(2026, 3, 5))));
System.out.println("a contains 2026-03-12: " + yn(a.contains(LocalDate.of(2026, 3, 12))));
try {
new DateRange(LocalDate.of(2026, 3, 10), LocalDate.of(2026, 3, 1));
} catch (IllegalArgumentException e) {
System.out.println("error: " + e.getMessage());
}
}
}
a equals b: yes
a and b are the same object: no
a: 2026-03-01..2026-03-10
c: 2026-03-01..2026-03-15
the room for b: room 4
a contains 2026-03-05: yes
a contains 2026-03-12: no
error: the end is before the start
- Verdict: native. A record has final fields and gets
equals,hashCodeandtoStringfrom its components. The compact constructor checks the rule of the value. ==compares references, so the program compares values withequals.LocalDateis itself a value object.
// A calendar day as a small value: three numbers.
const day = (y, m, d) => Object.freeze({ y, m, d });
const dayKey = (t) => `${t.y}-${String(t.m).padStart(2, "0")}-${String(t.d).padStart(2, "0")}`;
const before = (s, t) => dayKey(s) < dayKey(t); // ISO strings sort as dates
class DateRange {
#start;
#end;
constructor(start, end) {
if (before(end, start)) throw new Error("the end is before the start");
this.#start = start;
this.#end = end;
Object.freeze(this);
}
// JavaScript compares objects by identity, so the value object defines equals and a key.
equals(other) {
return this.key() === other.key();
}
key() {
return `${dayKey(this.#start)}..${dayKey(this.#end)}`;
}
contains(t) {
return !before(t, this.#start) && !before(this.#end, t);
}
extendTo(end) {
return new DateRange(this.#start, end); // a new value; this does not change
}
toString() {
return this.key();
}
}
const yn = (b) => (b ? "yes" : "no");
const a = new DateRange(day(2026, 3, 1), day(2026, 3, 10));
const b = new DateRange(day(2026, 3, 1), day(2026, 3, 10));
console.log("a equals b:", yn(a.equals(b)));
console.log("a and b are the same object:", yn(a === b));
const c = a.extendTo(day(2026, 3, 15));
console.log(`a: ${a}`);
console.log(`c: ${c}`);
const rooms = new Map([[a.key(), "room 4"]]); // a Map key must be a primitive to match by value
console.log("the room for b:", rooms.get(b.key()));
console.log("a contains 2026-03-05:", yn(a.contains(day(2026, 3, 5))));
console.log("a contains 2026-03-12:", yn(a.contains(day(2026, 3, 12))));
try {
new DateRange(day(2026, 3, 10), day(2026, 3, 1));
} catch (e) {
console.log("error:", e.message);
}
a equals b: yes
a and b are the same object: no
a: 2026-03-01..2026-03-10
c: 2026-03-01..2026-03-15
the room for b: room 4
a contains 2026-03-05: yes
a contains 2026-03-12: no
error: the end is before the start
- Verdict: idiom. JavaScript compares objects by identity, and a
Mapfinds an object key by identity. The class definesequalsand a stringkey(), and the map uses the key. Object.freeze(this)and private fields stop changes to the object after the constructor.
package main
import (
"errors"
"fmt"
)
// Day is a calendar day. A struct of comparable fields is comparable with ==.
type Day struct{ Y, M, D int }
func (t Day) before(u Day) bool {
if t.Y != u.Y {
return t.Y < u.Y
}
if t.M != u.M {
return t.M < u.M
}
return t.D < u.D
}
func (t Day) String() string { return fmt.Sprintf("%04d-%02d-%02d", t.Y, t.M, t.D) }
// DateRange is a value: unexported fields, no setters, and methods with value receivers.
type DateRange struct{ start, end Day }
func NewDateRange(start, end Day) (DateRange, error) {
if end.before(start) {
return DateRange{}, errors.New("the end is before the start")
}
return DateRange{start, end}, nil
}
func (r DateRange) Contains(t Day) bool { return !t.before(r.start) && !r.end.before(t) }
// ExtendTo returns a new value; r does not change.
func (r DateRange) ExtendTo(end Day) (DateRange, error) { return NewDateRange(r.start, end) }
func (r DateRange) String() string { return r.start.String() + ".." + r.end.String() }
func yn(b bool) string {
if b {
return "yes"
}
return "no"
}
func main() {
a, _ := NewDateRange(Day{2026, 3, 1}, Day{2026, 3, 10})
b, _ := NewDateRange(Day{2026, 3, 1}, Day{2026, 3, 10})
fmt.Println("a equals b:", yn(a == b))
fmt.Println("a and b are the same object:", yn(&a == &b))
c, _ := a.ExtendTo(Day{2026, 3, 15})
fmt.Println("a:", a)
fmt.Println("c:", c)
rooms := map[DateRange]string{a: "room 4"}
fmt.Println("the room for b:", rooms[b])
fmt.Println("a contains 2026-03-05:", yn(a.Contains(Day{2026, 3, 5})))
fmt.Println("a contains 2026-03-12:", yn(a.Contains(Day{2026, 3, 12})))
if _, err := NewDateRange(Day{2026, 3, 10}, Day{2026, 3, 1}); err != nil {
fmt.Println("error:", err)
}
}
a equals b: yes
a and b are the same object: no
a: 2026-03-01..2026-03-10
c: 2026-03-01..2026-03-15
the room for b: room 4
a contains 2026-03-05: yes
a contains 2026-03-12: no
error: the end is before the start
- Verdict: native. A struct whose fields are all comparable can be compared with
==and used as a map key. Unexported fields and a constructor function keep the rule of the value. - A Go struct is copied when it is assigned or passed, so two variables never share one
DateRange.&a == &bcompares the addresses of the two variables.
use std::collections::HashMap;
use std::fmt;
// A calendar day. The derived order compares the year, then the month, then the day.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
struct Day {
y: i32,
m: u32,
d: u32,
}
fn day(y: i32, m: u32, d: u32) -> Day {
Day { y, m, d }
}
impl fmt::Display for Day {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:04}-{:02}-{:02}", self.y, self.m, self.d)
}
}
// Private fields and no setters: a DateRange cannot change after it is created.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
struct DateRange {
start: Day,
end: Day,
}
impl DateRange {
fn new(start: Day, end: Day) -> Result<DateRange, &'static str> {
if end < start {
return Err("the end is before the start");
}
Ok(DateRange { start, end })
}
fn contains(&self, t: Day) -> bool {
self.start <= t && t <= self.end
}
// A new value; self does not change.
fn extend_to(&self, end: Day) -> Result<DateRange, &'static str> {
DateRange::new(self.start, end)
}
}
impl fmt::Display for DateRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}..{}", self.start, self.end)
}
}
fn yn(b: bool) -> &'static str {
if b { "yes" } else { "no" }
}
fn main() {
let a = DateRange::new(day(2026, 3, 1), day(2026, 3, 10)).unwrap();
let b = DateRange::new(day(2026, 3, 1), day(2026, 3, 10)).unwrap();
println!("a equals b: {}", yn(a == b));
println!("a and b are the same object: {}", yn(std::ptr::eq(&a, &b)));
let c = a.extend_to(day(2026, 3, 15)).unwrap();
println!("a: {}", a);
println!("c: {}", c);
let rooms = HashMap::from([(a, "room 4")]);
println!("the room for b: {}", rooms[&b]);
println!("a contains 2026-03-05: {}", yn(a.contains(day(2026, 3, 5))));
println!("a contains 2026-03-12: {}", yn(a.contains(day(2026, 3, 12))));
if let Err(e) = DateRange::new(day(2026, 3, 10), day(2026, 3, 1)) {
println!("error: {}", e);
}
}
a equals b: yes
a and b are the same object: no
a: 2026-03-01..2026-03-10
c: 2026-03-01..2026-03-15
the room for b: room 4
a contains 2026-03-05: yes
a contains 2026-03-12: no
error: the end is before the start
- Verdict: native.
#[derive(PartialEq, Eq, Hash)]gives equality and a hash from the fields.Copymakes each assignment a copy, and a value withoutmutcannot change. std::ptr::eqcompares addresses, so it shows thataandbare two objects with equal values.
Consequences
Benefits.
- Correct comparisons. Two values that are the same compare as equal, in tests, in sets and as map keys.
- No aliasing bugs. An immutable value can be shared by many objects, and no change in one place can surprise another.
- Rules in one place. The constructor checks the value once. Fowler writes that a telephone number object, in place of a string, gives "a natural focus for validation".2
- Safe for threads. An object that cannot change can be read by many threads with no lock.
Liabilities.
A mutable value that two owners share changes for both. In the following program, the stays of Ann and Bob use the same DateRange object. When Bob stays longer, the stay of Ann also changes.
This code runs but gives a wrong answer on purpose.
from datetime import date
class DateRange: # mutable, so two holders can share one object by mistake
def __init__(self, start, end):
self.start, self.end = start, end
def __str__(self):
return f"{self.start}..{self.end}"
march = DateRange(date(2026, 3, 1), date(2026, 3, 10))
stay_of_ann = march
stay_of_bob = march # the same object, not a copy
stay_of_bob.end = date(2026, 3, 15) # Bob stays five more days
print("Ann stays", stay_of_ann)
Ann stays 2026-03-01..2026-03-15
Make DateRange immutable, and let an extension return a new range. Then stay_of_bob = stay_of_bob.extend_to(...) changes only the variable of Bob. The bliki calls this kind of error an aliasing bug.2
More classes. Each kind of value is a class with its equality, hash and checks. In languages without records or data classes, this is much code to write and to keep correct.
Copies cost memory and time. Each change makes a new object. For a large value that changes often, the copies can be slow.
Storage needs a mapping. A value object has no key of its own, so a database does not keep it in a table of its own. It is usually saved as an Embedded Value in the row of its owner, or as a Serialized LOB.4
When not to use it
When the thing has an identity. A customer, an order or a bank account stays the same thing when its fields change, so it is a reference object or an entity, compared by its key. The bliki adds that an immutable sales order is still not a value object "if I'm determining equality based on a unique order number".2
When the context needs references. Fowler gives the example of a postal address, which can be a value in one program and a reference in a mapping system: "different contexts lead to different solutions."2
Variants and related patterns
Domain-driven design. The term has the same meaning in domain-driven design. "In Domain-Driven Design the Evans Classification contrasts value objects with entities."2 An entity has an identity that continues over time. A value object has none. The Domain model of a program uses both.
Records and data classes. Java records "act as transparent carriers for immutable data".5 They get "equals and hashCode methods which ensure that two record values are equal if they are of the same type and contain equal component values".5 Python data classes, C# records and Kotlin data classes give the same result.
Copies on assignment. Fowler notes that a language can also prevent aliasing bugs when each assignment makes a copy: "Some languages provide this ability, such as structs in C#."2 Go structs and Rust Copy types work in the same way.
Related patterns. A Money object is a common value object. The refactoring Change reference to value turns a reference object into a value object. A Data transfer object is a different pattern, but the Java community once used the name value object for it, as that page explains. An Immutable object can be a value object or a reference object.
Known uses
- Java records are value-like carriers of data with equality from their components.5
- Python data classes with
frozen=Trueand the defaulteq=Trueare hashable values that cannot be assigned to.3
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Value Object, pattern summary
- Martin Fowler, ValueObject, bliki, 14 November 2016, whole article
- Python documentation, dataclasses, Data Classes, the dataclass decorator, parameters eq, frozen and unsafe_hash
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Value Object
- OpenJDK, JEP 395, Records, Summary and Description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 77FJ1E Edit this page History Report an error Markdown