Quick revision
The short answer
A Lombok builder makes every field optional, so nothing stops build() from creating an object with no customer or no lines. We fix this without a rewrite by moving the rules into one place that every path goes through: a constructor or static factory that validates, with @Builder placed on it instead of on the class. For aggregates we add intention-revealing factories such as Order.place(customer, lines) and keep builders for tests and DTOs, add Bean Validation at the boundaries and NOT NULL and CHECK constraints in the database, and roll this out module by module with static analysis rules that flag @Builder on entities and aggregates.
What to remember
In this answer, we saw that Lombok builders make every field optional, so invalid objects are easy to build. We moved invariants into a validating constructor with @Builder placed on it, which keeps call sites working while rejecting bad objects, gave aggregates intention-revealing factories and kept builders for tests and DTOs, added Bean Validation at the boundaries and database constraints as the last line, and rolled the change out aggregate by aggregate with a static analysis rule to keep it from coming back.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A Lombok builder makes every field optional, so nothing stops build() from creating an object with no customer or no lines. We fix this without a rewrite by moving the rules into one place that every path goes through: a constructor or static factory that validates, with @Builder placed on it instead of on the class. For aggregates we add intention-revealing factories such as Order.place(customer, lines) and keep builders for tests and DTOs, add Bean Validation at the boundaries and NOT NULL and CHECK constraints in the database, and roll this out module by module with static analysis rules that flag @Builder on entities and aggregates.
Why this question is asked
Invalid objects reaching the database are expensive: they break reports, fail later jobs, and are hard to clean up because by the time we notice, other data depends on them. When the cause is how objects are built, the fix has to change habits across many teams, and we cannot stop feature work for a rewrite. Interviewers ask this design question to see whether we can find the root cause and apply a fix that spreads safely. In this answer, we will see why builders let invalid objects through, move invariants into one place, give aggregates proper factories, add the outer safety layers, and plan the rollout.
1Why Builders Let Invalid Objects Through
An invariant is a rule that must always be true for an object, for example "an order has a customer and at least one line". With @Builder on a class, Lombok generates a builder whose every setter is optional and a build() that passes whatever was set, including nulls, to an all-args constructor that checks nothing. So Order.builder().build() compiles and runs, and so does an order with a negative quantity.
Builders spread through a codebase because they are pleasant to use, and each call site sets the fields its author remembered. Over time, one service forgets the currency, a batch job forgets the customer, and a test helper sets status to null. None of these are compile errors, and the database accepts what it is given.
2Put the Invariants in One Place
The key move is to make every way of creating the object pass through code that checks the rules. That code is a constructor. If we put @Builder on a constructor we write, instead of on the class, the builder still works for every caller, but build() now calls our constructor, which validates.
Notice that existing call sites do not change: they still call Order.builder()...build(). The ones that were building invalid orders now fail loudly at the moment of creation, with a clear message, instead of quietly storing bad data. That is exactly what we want, and it lets us find the bad call sites through tests and logs.
3Give Aggregates Intention-Revealing Factories
For the central domain objects, the aggregates that own other objects and enforce business rules, a builder is the wrong interface even with validation, because it describes fields rather than business actions. An order is not "a thing with a customer field"; it is placed by a customer. A factory method says so, takes exactly the mandatory arguments, and leaves nothing to forget.
Builders stay where they shine: in tests, where we want to set up many variations quickly, and for DTOs and value objects with many optional fields. A test-only builder in the test source set, for example an OrderFixtures class, keeps that convenience without exposing a loose builder to production code.
4Add the Outer Safety Layers
Validation in constructors protects the domain model. Two more layers catch what slips past it. At the boundaries, request DTOs carry Bean Validation annotations such as @NotNull, @NotEmpty and @Positive, checked by @Valid in controllers, so bad input is rejected with a 400 before it reaches the domain. And in the database, NOT NULL, CHECK and foreign key constraints are the last line of defence: whatever code path writes the row, the database refuses an order without a customer.
- API boundaryBean Validation on request DTOs, 400 on bad input
- Domain factory
Order.place(customer, lines): mandatory arguments only - Constructorvalidates invariants;
@Buildersits on it - DatabaseNOT NULL, CHECK and foreign keys as the last line
4 layers, from the top down. Step through them one at a time.
Each layer catches a different kind of mistake.
Adding constraints to existing tables requires cleaning up the invalid rows already there, so each constraint comes with a data fix and a migration.
5Rolling It Out Without a Rewrite
We cannot change every module at once, so we go aggregate by aggregate, starting with the ones that have produced bad data. For each: move @Builder from the class to a validating constructor, run the test suite and fix the call sites that were building invalid objects, add the factory for the main production path, then add the database constraints after cleaning the data. Each step is a small, reviewable change.
To stop the pattern returning, we add a static analysis rule that fails when @Builder sits directly on a class annotated @Entity or on an aggregate class. Because @Builder has source retention, a bytecode tool such as ArchUnit checks its effect instead, such as a generated builder() method on an entity, with a short reviewed list of exceptions for builders that sit on validating constructors. The guideline goes into the handbook with the reason, and the review checklist asks where the invariants are enforced.
- Move @Builder to a validating constructorcall sites unchanged
- Run tests and fix failing call sitesthese were the bad ones
- Add the production factory
Order.place(customer, lines) - Clean data, add constraintsNOT NULL and CHECK in a migration
- Enable the analysis ruleno
@Builderon the class itself
5 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Why not just add @NonNull to every field?
It helps for nulls and costs little, so it is a fine first step. But invariants are often more than not-null: at least one line, quantity above zero, currency matching the customer. Those need real code, and that code belongs in the constructor or factory.
Won't failing constructors break production?
They will reject objects that were invalid anyway, which were already causing damage later. We roll out with tests and staging first, and we can log violations for a short period before turning them into exceptions if the risk is high.
Should entities be the domain model?
That is a separate design choice. Whether the domain objects are JPA entities or separate classes mapped to them, the rule is the same: one place enforces the invariants, and every path goes through it.
7Conclusion
In this answer, we saw that Lombok builders make every field optional, so invalid objects are easy to build. We moved invariants into a validating constructor with @Builder placed on it, which keeps call sites working while rejecting bad objects, gave aggregates intention-revealing factories and kept builders for tests and DTOs, added Bean Validation at the boundaries and database constraints as the last line, and rolled the change out aggregate by aggregate with a static analysis rule to keep it from coming back.
Open with
The root cause is that a Lombok builder treats every field as optional and its build calls an all-args constructor that checks nothing, so each call site sets what its author remembered and invalid orders get saved.
Then, if they want more
I would not rewrite anything. First I would put the invariants in one place: move @Builder off the class and onto a constructor I write, which validates, for example requireNonNull for the customer and at least one line.
Existing calls to builder and build keep compiling, but the bad ones now fail at creation with a clear message, which shows us where they are.
Second, for aggregates I would add intention-revealing factories like Order.place(customer, lines), which take exactly the mandatory arguments, and use them as the production path, keeping builders for tests and DTOs, ideally test fixtures in the test source set.
Third, I would add the outer layers: Bean Validation on request DTOs at the API boundary, and NOT NULL, CHECK and foreign key constraints in the database as the last line, after cleaning the existing bad rows.
I would roll it out aggregate by aggregate, starting with those that produced bad data, and add a static analysis rule that flags @Builder directly on entity and aggregate classes, so the pattern does not come back.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Teams use @Builder on domain objects in a large codebase, and invalid objects (missing...": https://scrivio-interview-library.netlify.app/java/lombok/937dc0323a/