Learn

Architecture & pattern guides

Read the idea, build it on a Grid, prove it in a challenge. Short, practical guides — illustrated with RodGrid's own nodes — on system design, design patterns, flow modeling, and how to get the most out of the app.

All articles

Value Object

Why bare numbers and strings let kilograms be compared with pounds, and how a value object fixes it: an object with no identity, equal to any other with the same values, immutable so operations return new values, and valid from its constructor, plus how the same concept can be a value in one model and an entity in another.

24,000 is not more than 44,000

A freight forwarder books a truck to take a 40-foot container from the port of Houston to a customer's warehouse. Before confirming, the booking code checks that the trucking company's chassis can carry the box: if (container.grossWeight > chassis.maxPayload) reject(). The container weighed 24000 and the chassis was rated for 44000, so the check passed and the booking went through. The terminal's weighbridge stopped the truck at the gate, about 8,900 pounds over the rating.

Both numbers were right. The forwarder records weights in kilograms; the trucking company's API reports ratings in pounds. In the code both were plain numbers, so the comparison set 24,000 kilograms against 44,000 pounds, and nothing in the program knew there was a difference to object to.

Modelling domain concepts with bare numbers and strings has a name: primitive obsession. A weight is an amount and a unit. A port code is a string with a format. A lane, the route a rate applies to, is a pair of ports. Pass them around as number and string and every function that receives one has to remember what it means.

A weight that knows its unit

The fix starts with a small type. Weight.kg(24000) and Weight.lb(44000) carry their units, and isGreaterThan converts before it compares, so the booking check now asks container.grossWeight.isGreaterThan(chassis.maxPayload) and gets the right answer. In a typed language, a raw number can no longer arrive where a weight is expected.

Weight is a Value Object: an object that describes something and is defined entirely by its values, with no identity of its own. A 24,000 kg weight on one container and a 24,000 kg weight on another are not two weights that happen to match. They are the same value, and either object could stand in for the other; nobody asks which 24,000 kg. Money, a date range and an address are the textbook examples.

Equal when the values are

The forwarder's next value was the lane. Rates are stored per lane, and the quoting code looked one up with rates.get(new Lane("NLRTM", "USHOU")), Rotterdam to Houston, and got nothing back, although the table held a rate for that lane. The map compared keys by reference: the Lane used to store the rate and the one built for the lookup were two objects, so to the map they were two keys.

A value object defines equality over its fields: two lanes are equal when their origins and destinations are equal. Where the language looks objects up by hash, the hash has to be computed from the same fields, or a hash map still misses; Java records and C# records generate both from their fields. JavaScript's Map always compares objects by reference, so the usual workaround there is to key the map by a string the value produces, such as NLRTM-USHOU. Weight makes a choice of its own: in this model, equivalent weights in different units are equal, so its equality and hash compare the amount converted to one unit and rounded to a precision the domain sets.

The consolidation that rebilled a customer

Smaller shipments travel together: the forwarder packs several customers' cargo into one container and sums their weights to plan the truck. The first Weight had an add method that changed the object it was called on, and the summing code started from the first shipment's weight: total = shipments[0].weight, then total.add(...) for each of the others. total was not a copy. It was the first shipment's own Weight, so with shipments of 1,200, 800 and 2,000 kg the first customer's shipment now said 4,000 kg, and that is what its invoice charged for.

A value object is immutable: once built, it never changes. Operations return a new value instead: a.plus(b) builds a third Weight and leaves a and b as they were, and when a shipper corrects a declared weight, the shipment gets a new Weight in place of the old one. The fields are read-only and hold only immutable values, a number and a unit, so the bug above cannot be written. Immutability is also what makes values safe to share: every shipment leaving Rotterdam can hold the same PortCode object, because none of them can change it under the others. That is the case for value objects in measurements and descriptors: immutability removes a whole class of bugs, those where two holders of one object see each other's changes. It is also why adding an id and setters to a value "just in case" backfires: it becomes an entity in disguise, and the identity and aliasing bugs it was meant to remove come back.

No such thing as a negative weight

A plain number also accepts things a weight never is: -500, Infinity, NaN from a failed parse. With bare numbers, the booking, rating and invoice code each checked for some of these, and a new report checked for none.

A value object checks its own rules in its constructor and refuses to exist if they fail. Weight rejects negative, infinite and non-numeric amounts and unknown units. PortCode takes a UN/LOCODE, two letters for the country and three characters for the place, letters or the digits 2 to 9, so PortCode("NLRTM") is built and PortCode("Rotterdam") throws. Once the constructor refuses, every Weight the code builds is a valid weight, and the code that receives one can stop checking for these; a separate validate() that callers are supposed to remember gives that back the day one of them forgets. Whether a well-formed code names a real port is a separate question, answered against the published list.

The check covers one value. A Weight can refuse to be negative; it cannot know that four shipments packed into the same container add up to more than the container may carry. Objects that must keep a joint rule after every change can form an Aggregate, whose root controls the changes.

One shipment, three values

The shipment is the root, tracked by its number. Its weight and lane are values, replaced whole when the shipper corrects them; the lane is built from two port codes, values inside a value.

A container is a value, until it is not

A shipper booking a 40-foot high-cube container takes any box of that type, so in the booking model the equipment is a value, compared by what it says. At the depot the same word means one numbered box with its own inspections and repairs, an Entity tracked by identity through a long life. Value or entity depends on whether the model cares which one, and the booking and the depot, often each in its own Bounded Context, answer differently.

Values in the aggregate

The Aggregate & Repository Challenge has a requirement that is about this article: "Connect the aggregate to the entities and value objects it owns". Use the shipment, or an aggregate from your own domain, and decide for each card whether it is a value: if swapping it for another card with the same contents would change nothing, it is a Value Object. On each value card write what its constructor refuses, as "no negative amounts" for a weight, and connect it only to what holds it. Then look for a number or string still sitting bare on the root, a weight without its unit or a port as free text, and ask whether it deserves a card of its own.

Practice this