Building a ChemDraw clone with DDD (Part II): Strict Value Objects & Error Boundaries
In my previous post, I laid down the basic entities and value objects to model the chemical domain. But there was a glaring flaw in the initial MVP: The Atom entity was too permissive. The problem:...

Source: DEV Community
In my previous post, I laid down the basic entities and value objects to model the chemical domain. But there was a glaring flaw in the initial MVP: The Atom entity was too permissive. The problem: Playing God Previously, the domain allowed you to instantiate an Atom with any string as its chemical element. You could play god and create a new 'Hydroxygen' atom without the system complaining. Obviously, in chemistry, the periodic table is a strictly closed set. The code needs to reflect that physical reality. The solution: A Closed Registry My solution was straightforward but rigorous. I created a strict ChemicalElement value object backed by a closed registry of valid elements. The factory method of this VO only accepts a valid chemical symbol, otherwise, it rejects the creation. To make this completely type-safe, I used a TypeScript generic trick to infer the literal types and guarantee that the object key always matches the element's symbol. Here's the code: export interface ElementD