Software Architecture

Domain-Driven Design: Value Objects—business concepts through values and immutability

Learn to represent concepts with Value Objects that validate their data, compare by value, and offer immutable operations. Implement Money, Email, and Address in TypeScript, use them within an Entity, and discover what to check when reviewing AI-generated code.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

A store receives two amounts: 1000 and 500. The backend adds them and returns 1500. The arithmetic is correct, but the first amount was in euro cents and the second in US dollar cents.

On another screen, someone interprets 1000 as one thousand euros. On a third, changing a product's price also changes the amount shared by an order line.

A number allows all those operations because it knows nothing about currency, unit, or meaning. A Value Object brings that knowledge into the model: it represents a business value together with the rules for creating, comparing, and using it.

What characterizes a Value Object

A Value Object is defined by the values it represents, without a conceptual identity of its own that you need to track over time. Two amounts of ten euros are equivalent for a calculation even if they come from different instances. This distinction appears in the Value Objects section of Eric Evans's DDD reference.

An Entity, by contrast, retains an identity: an order remains the same order even if its address changes. The address agreed for that order can be represented as a Value Object, because its contents matter rather than tracking an individual address's history.

When working with Value Objects, it is useful to combine four properties:

  • Compare them by their meaningful values.
  • Establish valid creation conditions.
  • Offer operations that respect their meaning.
  • Keep them immutable: changing a value means obtaining another one without altering the previous one.

Fowler explains the relationship between value comparison and immutability in his article on Value Object. Specific policies—which currencies to accept or how to compare email addresses—still belong to your model.

The absence of conceptual identity does not mean the object has no reference in memory. It means that reference does not decide whether two values are equivalent.

Primitive Obsession: when the type allows too much

Primitive Obsession describes excessive use of primitive types for concepts needing their own rules and meaning. Not every string should become a class. The signal appears when you repeat validations, confuse units, or perform operations the business does not allow. Fowler's Replace Primitive with Object refactoring proposes introducing objects when data starts needing that behavior.

This partial snippet illustrates the problem:

function calculateTotal(price: number, shipping: number): number {
  return price + shipping;
}

calculateTotal(1000, 500); // No expresa moneda ni unidad.

Adding names such as priceInCents helps, but does not prevent adding different currencies. We need the program to reject that operation, rather than merely warn about it in a comment.

Main example: Money with immutable operations

Defining the decisions before implementing

Our example accepts only euros and US dollars, represented as EUR and USD. We will work with integer minor units: 1050 represents 10.50 in either of those currencies. This convention is limited to the chosen currencies; it does not assume all currencies have two decimal places.

The rules will be:

  • The amount is a nonnegative safe integer.
  • Only amounts in the same currency can be added.
  • Multiplication requires a nonnegative integer quantity.
  • Each operation validates its result and returns another instance.

We do not model debts, conversions, percentages, or rounding. A business that needs them must explicitly define those operations. Nor will we accept decimals and then multiply them by one hundred: the input must already express minor units.

Complete program

This block is self-contained. Save it as money.ts and run it with node money.ts on Node.js 24.21.0. It only requires modules included in Node.js. The article's other two programs run in the same way, each in its own file.

Node executes this syntax through type stripping, which removes TypeScript annotations; it does not perform static type checking. That is why important conditions are also checked at runtime.

import assert from 'node:assert/strict';

type Currency = 'EUR' | 'USD';

class Money {
  readonly minorUnits: number;
  readonly currency: Currency;

  private constructor(minorUnits: unknown, currency: unknown) {
    if (
      typeof minorUnits !== 'number' ||
      !Number.isSafeInteger(minorUnits) || minorUnits < 0
    ) {
      throw new Error('El importe debe ser un entero seguro no negativo');
    }
    if (currency !== 'EUR' && currency !== 'USD') {
      throw new Error('Moneda no admitida');
    }
    this.minorUnits = minorUnits;
    this.currency = currency;
    Object.freeze(this);
  }

  static create(minorUnits: unknown, currency: unknown): Money {
    return new Money(minorUnits, currency);
  }

  add(other: Money): Money {
    if (this.currency !== other.currency) {
      throw new Error('No se pueden sumar monedas distintas');
    }
    return Money.create(this.minorUnits + other.minorUnits, this.currency);
  }

  multiply(quantity: number): Money {
    if (!Number.isSafeInteger(quantity) || quantity < 0) {
      throw new Error('La cantidad debe ser un entero seguro no negativo');
    }
    return Money.create(this.minorUnits * quantity, this.currency);
  }

  equals(other: Money): boolean {
    return this.minorUnits === other.minorUnits && this.currency === other.currency;
  }

  toDTO(): { minorUnits: number; currency: Currency } {
    return { minorUnits: this.minorUnits, currency: this.currency };
  }
}

const unitPrice = Money.create(1250, 'EUR');
const shipping = Money.create(350, 'EUR');
const subtotal = unitPrice.multiply(2);
const total = subtotal.add(shipping);

assert.equal(total.minorUnits, 2850);
assert.equal(unitPrice.minorUnits, 1250);
assert.equal(subtotal.minorUnits, 2500);
assert.notEqual(total, subtotal);

const sameValue = Money.create(2850, 'EUR');
assert.equal(total === sameValue, false);
assert.equal(total.equals(sameValue), true);
assert.equal(total.equals(Money.create(2850, 'USD')), false);

assert.throws(() => total.add(Money.create(1, 'USD')), /monedas distintas/);
assert.throws(() => Money.create(10.5, 'EUR'), /entero seguro/);
assert.throws(() => Money.create(-1, 'EUR'), /no negativo/);
assert.throws(() => Money.create(1, 'CLP'), /Moneda no admitida/);
assert.throws(() => unitPrice.multiply(1.5), /cantidad/);
assert.throws(() => Money.create(Number.MAX_SAFE_INTEGER, 'EUR')
  .add(Money.create(1, 'EUR')), /entero seguro/);

assert.throws(() => Object.assign(unitPrice, { minorUnits: 1 }), TypeError);
assert.deepEqual(total.toDTO(), { minorUnits: 2850, currency: 'EUR' });
console.log('Money: igualdad, operaciones y límites verificados');

From inputs to result

The inputs are two units at EUR 12.50 and shipping of EUR 3.50. multiply(2) produces EUR 25.00; add(shipping) produces EUR 28.50. The unit price and subtotal do not change.

If shipping were in USD, addition would fail. If an operation exceeds JavaScript's safe integer range, creating the result also fails. Using integers removes the need to add decimals in this example, but does not turn number into an unlimited-precision type.

The Invariant, a condition that must hold for every valid instance, combines the accepted amount and currency here. Validating results too prevents an operation from starting with valid values and producing another value the model cannot represent.

Notice the distinction between reference and value: total === sameValue is false because they are different objects; equals() returns true because amount and currency match. JavaScript does not automatically invoke that method when using ===. Nor does a Set of objects deduplicate two instances using your equals(); if you need that collection, you must define its key or comparison criterion.

Immutability: readonly is not enough

In TypeScript, readonly communicates a restriction to the type checker, but does not itself change runtime behavior. In addition, a read-only property can point to an object whose contents remain mutable. The official TypeScript documentation explains both limitations.

In Money, Object.freeze(this) prevents modifying its properties at runtime. Since they contain only primitive values, that is enough for this design. It is not a general recipe: freezing an object does not recursively freeze its nested arrays or objects, nor make every class's internal data immutable. The Object.freeze documentation on MDN details these limits.

If you use private fields with #, the class must also refrain from mutating them; Object.freeze() does not turn those fields into constants. Immutability depends on the complete design, not an isolated keyword.

The practical advantage is being able to share a value without one consumer altering it for another. Changing the price means assigning another Money where appropriate, not rewriting the previous one.

Email: validating a policy and deciding equality

In an educational platform, an email represented as a string may be empty, include surrounding spaces, or use an unsupported format. An Email can centralize that policy and offer consistent comparison.

But normalization is not a neutral task. The SMTP standard distinguishes the local part, before @, from the domain name: the former must preserve its letter case; the latter is case-insensitive. This is established in RFC 5321, section 2.3.11. We will not lowercase the entire address or remove dots or tags such as +curso.

This self-contained program for email.ts deliberately accepts an ASCII subset: a local part with letters, numbers, dots, and some symbols; a domain with dot-separated labels. It rejects other formats that may be valid under the standards. This is an instructional policy, not a complete international email validator. A real application must choose validation appropriate to its requirements.

import assert from 'node:assert/strict';

class Email {
  readonly value: string;

  private constructor(input: unknown) {
    if (typeof input !== 'string') throw new Error('El correo debe ser texto');
    const parts = input.trim().split('@');
    if (parts.length !== 2) throw new Error('Formato no admitido');
    const [local, domain] = parts;
    const validLocal = /^[A-Za-z0-9._%+-]+$/.test(local) &&
      !local.startsWith('.') && !local.endsWith('.') && !local.includes('..');
    const validDomain = domain.split('.').length >= 2 &&
      domain.split('.').every(label =>
        /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(label));
    if (!validLocal || !validDomain) throw new Error('Formato no admitido');
    this.value = `${local}@${domain.toLowerCase()}`;
    Object.freeze(this);
  }

  static create(input: unknown): Email {
    return new Email(input);
  }

  equals(other: Email): boolean {
    return this.value === other.value;
  }
}

class Student {
  #id: string;
  #email: Email;

  constructor(id: string, email: Email) {
    if (!id.trim()) throw new Error('El estudiante necesita identidad');
    this.#id = id;
    this.#email = email;
  }

  get id(): string { return this.#id; }
  get email(): Email { return this.#email; }

  changeContactEmail(email: Email): void {
    this.#email = email;
  }
}

const original = Email.create('  Ana@EXAMPLE.COM  ');
assert.equal(original.value, 'Ana@example.com');
assert.equal(original.equals(Email.create('Ana@example.com')), true);
assert.equal(original.equals(Email.create('ana@example.com')), false);
assert.throws(() => Email.create('sin-arroba'), /Formato/);
assert.throws(() => Email.create('ana..diaz@example.com'), /Formato/);

const student = new Student('student-1', original);
student.changeContactEmail(Email.create('Ana+curso@example.com'));
assert.equal(student.id, 'student-1');
assert.equal(student.email.value, 'Ana+curso@example.com');
assert.equal(original.value, 'Ana@example.com');
console.log('Email: normalización, igualdad y reemplazo verificados');

The result shows two different decisions. Email protects a format and an equality policy; Student retains its identity while replacing one contact value with another. The Entity can expose the Email because it does not allow its properties to be mutated.

Validation does not prove that the mailbox exists, receives messages, or belongs to the student. Verifying control of an email address is another process. The example changes contact data; it does not implement a secure login credential change or an account uniqueness policy.

Length limits and other protocol restrictions also remain out of scope. That omission is limited to the example: do not present its regular expression as a universal solution.

Address: a composite value replaced as a whole

In logistics, an address can mix street, city, and postal code in a single string. Separating components facilitates validation and comparison, but allowing arbitrary modification can still affect several consumers.

This program for address.ts represents a minimal address in a local workflow. It requires three nonempty components and trims surrounding spaces. It does not validate country-specific postal codes, coordinates, or physical existence. Nor does it claim that two texts a person considers equivalent are the same address: the chosen equality compares normalized components exactly.

import assert from 'node:assert/strict';

type AddressInput = { street: unknown; city: unknown; postalCode: unknown };

function requireText(value: unknown, label: string): string {
  if (typeof value !== 'string' || !value.trim()) {
    throw new Error(`${label} es obligatorio`);
  }
  return value.trim();
}

class Address {
  readonly street: string;
  readonly city: string;
  readonly postalCode: string;

  private constructor(input: AddressInput) {
    this.street = requireText(input.street, 'La calle');
    this.city = requireText(input.city, 'La ciudad');
    this.postalCode = requireText(input.postalCode, 'El código postal');
    Object.freeze(this);
  }

  static create(input: AddressInput): Address {
    return new Address(input);
  }

  withStreet(street: unknown): Address {
    return Address.create({ street, city: this.city, postalCode: this.postalCode });
  }

  equals(other: Address): boolean {
    return this.street === other.street && this.city === other.city &&
      this.postalCode === other.postalCode;
  }

  toDTO(): { street: string; city: string; postalCode: string } {
    return { street: this.street, city: this.city, postalCode: this.postalCode };
  }
}

const destination = Address.create({
  street: '  Calle Central 10 ', city: 'Ciudad Ejemplo', postalCode: '12345',
});
const corrected = destination.withStreet('Calle Central 12');
assert.equal(destination.street, 'Calle Central 10');
assert.equal(corrected.street, 'Calle Central 12');
assert.equal(destination.equals(corrected), false);
assert.equal(destination.equals(Address.create(destination.toDTO())), true);
assert.throws(() => destination.withStreet('   '), /obligatorio/);

const dto = destination.toDTO();
dto.city = 'Otra ciudad';
assert.equal(destination.city, 'Ciudad Ejemplo');
console.log('Address: igualdad y reemplazo inmutable verificados');

Changing the street produces another value and preserves the previous one. The operation retains the city and postal code, but does not verify that the new combination exists; an address verification process may be necessary depending on the business.

If an address becomes fixed when an order is dispatched, having an immutable Value Object is not enough. The Entity representing that order must decide when replacement is allowed. Value immutability and its owner's replacement rules solve different problems.

The three self-contained programs were run with Node.js 24.21.0 and completed their included assertions. No static analysis with the TypeScript compiler or validation against external services was performed.

Value Object, Entity, primitive, and DTO

The primitive is the basic representation: number or string. A Value Object combines components, rules, and operations for a specific meaning. An Entity maintains identity while evolving.

A DTO, or Data Transfer Object, transports data across boundaries. The object returned by Money.toDTO() expresses amount and currency without retaining methods or constructor guarantees. Having the same field shape does not make it a valid Money.

When receiving external data, check its structure and reconstruct the Value Object through its validated creation mechanism. Do not use a cast such as data as Money: it changes what TypeScript assumes, but does not validate or construct the instance.

Equality also depends on purpose. An entry stored in an address book can have its own identity and remain the same entry even when edited. The address copied into an order can be a value. The concept is modeled according to responsibility, not its name.

Which invalid states you can prevent and which you cannot

The examples prevent constructing negative amounts under this policy, adding different currencies, and accepting empty components. These guarantees cover the implemented rules and normal creation and usage paths.

They do not prevent a commercially incorrect price that is nevertheless a valid integer. Nor do they guarantee permissions, stock, email delivery, or consistency between processes. A Value Object represents explicit knowledge; it does not guess missing rules.

Static methods make creation readable, but private on a TypeScript constructor does not constitute a runtime security boundary. We kept validations inside constructors so they do not depend solely on the static method.

When a primitive type is enough

An optional label used once to display a message can remain a string. A local loop counter does not need IterationCount if it does not represent a business decision.

Introduce a Value Object when it centralizes shared rules, prevents unit confusion, or adds meaningful operations. If a class merely wraps a value without clarifying decisions or reducing concrete errors, consider the cost of more names, conversions, and files.

Immutability may also involve creating more objects. Usually, prioritize clarity and measure whether a performance problem exists before replacing it with shared mutations. You do not need a base class or a generic equality system for these examples.

Prompts for working with AI without losing meaning

Detecting concepts hidden in primitives

Analyze this price calculation. We work only with EUR and USD, in nonnegative integer minor units. Look for currency and unit confusion and duplicated validations. Do not change files or add conversions. Return Value Object proposals and counterexamples justifying each one. A person will confirm currencies, rounding, and whether negative amounts are allowed before implementation.

Implementing immutable operations

Implement Money in TypeScript without dependencies, with validated creation, equals, add, and multiply. Accept only EUR and USD, and reject amounts or results outside the nonnegative safe integer range. Do not modify existing instances. Provide a self-contained program and assertions for different currencies, value equality, overflow, and operand preservation. A person will run the tests and check the agreed monetary rules.

Reviewing validation and normalization limits

Review Email and Address against the attached policies. Look for meaning-changing normalizations, incomplete equality, exposed mutable references, and DTOs treated as validated instances. Do not edit files or claim a regex verifies mailbox existence or ownership. Return evidence, one scenario per finding, and outstanding questions. A person will validate policies with the business and external system requirements.

A test generated by the same AI may repeat an incorrect decision. Review counterexamples and policy before accepting that a class is correct because all its tests pass.

Three exercises with reasoned solutions

1. A ten-percent discount

A proposal adds multiply(0.9) to apply a discount to Money. Is it compatible with the example?

Reasoned solution: no; the method represents an integer quantity, not a percentage. You need another operation with an explicit rounding policy and handling of fractions of a minor unit. Also decide whether rounding occurs per line or on the total, and check cases such as 101 minor units. Do not remove integer validation to hide that decision.

2. Two accounts with apparently the same email

A tool proposes removing dots and everything after + before comparing email addresses. Would you apply it to every provider?

Reasoned solution: not without a justified policy. Those transformations can merge distinct addresses. In the example, we normalize only the domain and surrounding spaces; a provider-specific equivalence requires explicit rules and scope. Also, email equality and account uniqueness policy are not automatically the same decision.

3. An array inside Address

street is replaced by lines: string[], and Object.freeze(this) is retained. Is that enough to maintain immutability?

Reasoned solution: no; the array can remain mutable and be shared with whoever supplied it. Copy and protect the internal collection, control what you expose, and check that modifying the input array or a read does not change the value. readonly and shallow freezing do not solve that aliasing—multiple references to the same mutable object—by themselves.

How to decide where to apply a Value Object

Look for concepts needing content-based comparison, repeated validations, or operations with their own units and constraints. First define which values you consider equivalent and which changes should produce a new instance.

Then check three things: creation rejects what is unsupported, operations preserve the rules, and no consumer can indirectly modify the shared value. With those criteria, you can evaluate a concrete implementation, whether you wrote it yourself or used AI to generate it.

Loading conversation…

Keep learning