Scrivio Interview library
LeadershipAdvanced6 min read · updated 12 November 2026

Your organisation has a mix of mutable JavaBeans with setters and newer immutable records across domain models. What standard would you set for new code and how would you handle existing code and frameworks that expect setters?

I would make immutable records or final classes the default for new value and domain types, while keeping JPA entities mutable because the persistence provider manages their state, and keeping the two kinds of type separate. Current Jackson, Spring binding and the main mappers work with constructors and records, so setters are rarely needed anymore. Existing JavaBeans migrate when they are touched, starting with types shared across threads or services, and exceptions are documented, with allocation measured where objects are created at very high rates.

Background to this question

Most long-lived Java codebases contain both styles: JavaBeans with a no-argument constructor and a setter per field, written when frameworks required them, and newer records. Mixing them without a rule creates confusion about which objects are safe to share and which can change under us. A senior engineer is expected to set a standard that improves safety without fighting the frameworks or stopping delivery for a rewrite. In this answer, we will look at why the default should change, where mutability must stay, how current frameworks handle immutable types, how to migrate existing code, and how to handle exceptions and performance concerns.

1Why Change the Default Now

A JavaBean is a class with a public no-argument constructor and a getter and setter for each property. The style came from early frameworks that created objects empty and then filled them in through setters. Its weakness is that any code holding a bean can change it at any time, so a DTO passed to a cache, an event or another thread may change after we hand it over, and a half-filled bean can exist with required fields still null.

A record states its data in one line, validates it in one constructor and cannot change afterwards. Bugs from shared mutable state disappear, equality is correct by default, and reviewers read less code. Since Java 16 records are standard, and the frameworks have caught up, so the old reason for setters is mostly gone. That is why I would make immutability the default for new types rather than a matter of taste.

2Where Mutability Stays: JPA Entities

JPA entities are the important exception. Hibernate and other providers create entities through a no-argument constructor, track changes to their fields to decide what to write (dirty checking), and replace lazy associations with proxies, which are generated subclasses. An entity therefore must not be final and must be mutable, and records cannot be entities.

The rule I would set is to keep the two worlds apart. Entities are mutable objects that live inside a transaction in the persistence layer. Everything that leaves that layer, such as API responses, events, cache entries and messages between modules, is an immutable record built from the entity. That boundary also stops lazy-loading surprises outside a transaction, because a record holds plain data rather than proxies. Records do work well as JPA embeddables in recent Hibernate versions and as projection results in queries, so check your version for embeddable support.

Step throughWhere each kind of type lives
  1. API and messagingimmutable records: requests, responses, events
  2. Service layerimmutable value types: Money, OrderId, DateRange
  3. Persistence layermutable JPA entities, managed inside transactions
  4. Databaserows

4 layers, from the top down. Step through them one at a time.

Entities are converted to records at the persistence boundary.

3What the Frameworks Support Today

The usual objection is that a framework needs setters. In current versions that is rarely true. Jackson 2.12 and later deserialises records through their canonical constructor without annotations, and plain final classes through a constructor annotated with @JsonCreator. Spring Boot binds @ConfigurationProperties to records through constructor binding, and Spring MVC binds request bodies and form objects to records. MapStruct maps into records and other constructor-based types. JPA projections can target records with a constructor expression.

Java
public record CustomerDto(String id, String name, List<String> tags) {
public CustomerDto { tags = List.copyOf(tags); }
}
@ConfigurationProperties("billing")
public record BillingProperties(Duration timeout, int retries) {} // bound through the constructor
// Jackson: {"id":"c1","name":"Ana","tags":["vip"]} -> new CustomerDto("c1", "Ana", List.of("vip"))

Where an older library still needs setters, that is a documented exception for that type, not a reason to keep the whole codebase mutable.

4Migrating Existing Beans

I would not run a big rewrite. Converting hundreds of beans at once is risky, produces huge reviews and mostly touches code that works. Instead, the rule is that a bean is migrated when a team changes it for another reason, with priority for the types where mutability is most dangerous: objects shared across threads, such as cached values and configuration, and objects that cross service or module boundaries, such as events and API types, where a change after sending can corrupt someone else's view.

A typical migration of a bean with callers that use setters goes through a builder or a static factory so that callers change in small steps, and tests for equality and JSON shape protect the wire format. A static analysis rule, for example in ArchUnit or Error Prone, can stop new setters appearing in packages already marked as immutable.

Step throughShould this bean be migrated now?
  1. Is it a JPA entity?
    Yeskeep it mutable; add a record for outside useNocontinue
  2. Is the team changing it anyway?
    YescontinueNoleave it for now
  3. Shared across threads or services?
    Yesmigrate firstNomigrate when convenient
  4. Convert to record or final classcopy collections in the constructor
  5. Check JSON and equality teststhe wire format must not change

5 steps in order. Play them, or step through them one at a time.

Migration follows the work teams are already doing.

5Exceptions and Allocation

Two kinds of exceptions should be written down rather than argued about in every review. The first is framework constraints: entities, a few legacy libraries that only use setters, and types generated from schemas. The second is performance in hot paths. An immutable object creates a new instance for every change, so code that updates a value millions of times per second, such as an accumulator in a tight loop, may allocate a lot.

In practice, the JVM handles short-lived objects very cheaply, and escape analysis can remove some allocations entirely, so most worries do not survive a measurement. The rule is therefore: measure with a profiler or JMH before granting a performance exception, and if the cost is real, keep the mutable object local to one method or one thread and expose an immutable result. That keeps the speed without letting mutable state spread.

6Follow-up questions

Should DTOs for incoming requests also be records?

Yes, they are among the best fits. A request body is data that should not change once parsed, and with a compact constructor we can validate it in one place. Bean Validation annotations such as @NotBlank work on record components, so validation stays declarative.

What about Lombok @Value and @Data?

@Value produces an immutable final class and is acceptable where records do not fit, for example when we need a class hierarchy. @Data generates setters, so it would fall under the same rule as hand-written beans: allowed for entities and documented exceptions, not as the default.

How do you convince teams that resist the change?

By showing the bugs it removes. A short internal write-up of one real incident, such as a cached object changed by a caller, is more persuasive than a style guide. Then make the right thing easy: templates, examples for Jackson and Spring binding, and lint rules, so the new default costs no extra effort.

7Conclusion

In this answer, we set a standard where new value and domain types are immutable records or final classes by default, because they remove shared-state bugs and current Jackson, Spring binding and mappers support them. JPA entities stay mutable because the provider manages them, and they stay separate from the records that leave the persistence layer. Existing beans migrate when touched, starting with types shared across threads or services, while exceptions for frameworks and hot paths are documented and backed by measurements of allocation rather than assumptions.

What to say in the interviewAbout 90 seconds aloud

Open with

For new code I would set immutability as the default: value types, DTOs, events, configuration and API types are records, or final classes when a record does not fit, with collections copied in the constructor.

Then, if they want more

The reason is that mutable beans can change after we hand them to a cache, an event or another thread, and they can exist half-filled. The old reason for setters has mostly gone: Jackson deserialises records through the canonical constructor, Spring Boot binds configuration properties to records, Spring MVC binds request bodies to them, and MapStruct maps into them.

The clear exception is JPA entities. The provider creates them empty, tracks changes and proxies them, so they stay mutable and non-final, and I keep them inside the persistence layer and convert to records at the boundary.

For existing code I would not do a big-bang rewrite; teams migrate a bean when they touch it for other work, starting with types shared between threads or crossing service boundaries, and with tests that check the JSON shape does not change. Any remaining exceptions, like legacy libraries that need setters or a genuinely hot path, are documented.

For the performance concern, I would ask for a measurement, because short-lived allocations are usually cheap, and when they are not, keep the mutable object local and expose an immutable result.

About this answer

Last updated
12 November 2026
Versions it names
Java 16
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 "Your organisation has a mix of mutable JavaBeans with setters and newer immutable...": https://scrivio-interview-library.netlify.app/java/immutability/25256b968d/