Should a request DTO be a Java value class?

November 16, 2026 4 answers
Asked by _e28~busnotch.7

For a type used to deserialize an HTTP request, when would a value class make more sense than a record or an ordinary class? Does the number of fields matter, for example if the DTO has 15 int fields?

Answers

_j87~parcelspanner.4

Start with semantics, not field count. A value class says its instances don't have identity. If two DTOs with the same contents are interchangeable for your purposes, that may be a good fit. If you need to distinguish two otherwise identical request objects by identity, it isn't.

Also, a record and a value class aren't the same choice. A record is a data carrier, while the value class distinction is about identity. A DTO can be immutable and still have identity.

_e28~busnotch.7:

So having lots of fields doesn't automatically rule out value semantics?

9j+socketruler_384:

Right. Size may affect performance, but it doesn't decide whether identity makes sense for the type.

Reply to this answer
5f+socketpuzzle_291

A record is a straightforward starting point for an immutable request DTO. It expresses the data carrier shape without making you depend on a newer feature. If the deserializer and the rest of your framework support value classes well, you can consider a value record when identity-free semantics are what you want.

Not every DTO needs to be immutable, though. Check how your deserialization and validation setup constructs and uses the object before choosing the declaration.

Reply to this answer
9t!clampnotch_361

Don't assume 15 ints means every method call copies 15 ints, or that a value class will automatically save memory. The representation and optimizations depend on the JVM and on how the object is used. Generic framework paths may also limit which optimizations are available.

For a performance-sensitive endpoint, benchmark the actual deserialization and request handling path on the Java version you plan to deploy. Allocation results from a small test or another setup won't necessarily predict yours, especially while the feature is in preview.

Reply to this answer
6t~ferryspanner_283

There's also an API design question. If the DTO is exposed to other code, changing its identity semantics later can affect callers that rely on identity. Treat that as part of the contract, not just an implementation detail.

Tervik-7p:

That matters less for a DTO kept entirely inside one service, but it's worth checking before publishing one as part of a shared API.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions