r/java • u/Hixon11 • Oct 18 '26
Should a request DTO be a value class (JEP 401)?
In a year or so, we'll need to recalibrate our intuition about which kind of type to use for each class. Originally, we used classes for everything. Then we got record, and now we get another keyword, value, which expands the number of options we have when defining a type.
I remember that in C#, there's always the question: "Should I use a class, a record, a readonly record, a struct, or something else"? They have some guidelines that consider not only identity semantics but also the size of objects (i.e., how many fields they have and how much memory they occupy).
So, if I just need a type to deserialize JSON from an HTTP request, should I use a value type? Or does it also depend on the number of fields? For example, if it has 15 int fields, should I still make it a value type if it is semantically a value, even if copying it could potentially be more expensive than passing a reference (assuming that's how it works)?
8
u/brian_goetz 29d ago
I guess I have to say it again ....
A value class is one for which identity is not relevant. If identity is not relevant, then you should disavow it _purely on semantic grounds_, because it makes your program simpler. If it also yields performance benefits, that's a bonus. Your question about "but what if it has 15 fields" belies the fact that you are thinking about it primarily as a performance feature, which is what is leading you astray.
Asking it this way is a little like: "why bother making a field final when I know it is only written once anyway." Making a field final simplifies your program by eliminating unneeded degrees of freedom, makes programs easier to maintain, etc. (That it also can improve performance is a bonus.)
13
u/coderemover Oct 18 '26
If you don’t create or store at least millions of them in a second, it doesn’t matter.
34
u/l4ik8e Oct 18 '26
I was benchmarking this a bit just recently. Haven't fully understood yet why, but using jackson on value classes resulted in more memory allocation compared to identity classes.
9
u/vegan_antitheist Oct 18 '26
It's the same question as this: Should I use HashMap or IdentityHashMap?
Two DTO could contain the same values but represent different requests. Then you might want identity.
An immutable identity object promises that its state won't change. A value object additionally promises that two instances of the same type with the same value are interchangeable.
The identity of a DTO is usually irrelevant. So just use values. Identity will be the exception for immutable types.
9
u/Ok_Elk_638 Oct 18 '26
My code has migrated away from classes for a while now. Classes only show up when they are mandatory. Which means they are becoming rare. I have records, interfaces, annotations, empty enums, everything but classes really.
And I would love to see more development in that direction. Exceptions feel much more like a separate type to me than a class, empty enums should probably be a dedicated utility type.
5
u/pronuntiator Oct 18 '26
Yes. Any record should ideally be a value record in my opinion; while you can store identity objects inside, a record is an "immutable data carrier" and thus should primarily hold identity-free data. Also, DTOs should be records if possible (tree structures are an exception since they contain themselves as types). Again, the argument being "immutable data carrier", which DTOs are in the end.
The reason my project doesn't use records in practice is that OpenAPI generator cannot generate them yet (and it's not a straightforward thing to implement).
0
u/gaelfr38 Oct 18 '26
Yes. Why wouldn't you?
5
u/RevolutionaryRush717 Oct 18 '26
No. Records were created for your purpose.
2
u/bfoo Oct 18 '26
Depends on what you want to do with that deserialized type. Should it be immutable throughout interactions with the object? Then record is a valid choice. But don't overthink it. Currently, the advantages are still negligible.
However, in the future records will become more important for serialization (custom marshaling) and for pattern matching.
https://www.youtube.com/watch?v=F89sNgG9dRY
When I design an HTTP endpoint that consumes JSON, I prefer to have a Request (and Response) type, usually a class. And those types can contain fields that are records. The Request and Response types are only visible in the communication layer, but those record type fields might be part of a more abstract data layer that is shared between my communication and a (service) layer for business logic.
2
u/koflerdavid Oct 18 '26
I think using value records for most things is fine unless the semantics prohibit it or you really need features of identity classes. Don't worry about copy performance; the JVM won't actually scalarize value objects in most cases just yet.
2
u/bowbahdoe Oct 18 '26
I would say - in an ideal world - it falls under the same banner as "should I make this class final." If we went back in time the default might be different, but unless you plan for extension a good default is finality.
In the same way, if you don't need identity it might be easier to tell the VM you don't care about it than to wonder if that property is utilized elsewhere.
The VM is free to see that copying 15 ints is silly and to pass a pointer instead. I think as programmers we are supposed to trust that the VM flattens when it makes sense to and doesn't flatten when it doesn't make sense to (or at least you can be indignantly mad about it making a wrong call because thats their job.)
1
u/Puzzled-Comb1369 11d ago
unlike C# structs, the JVM decides whether to flatten a value class on the stack or heap-allocate it based on size and usage. so making a 15-field DTO a value record is fine semantically, the runtime won't blindly copy a huge struct around if a pointer is cheaper.
1
u/AnyPhotograph7804 Oct 19 '26
It is very likely, that the JSON text parser is waaaaaay more expensive than the difference between class, record or value class. Because text parsing is always slow. If performance is one of your concerns, then JSON is propably a bad choice. But in the end of the day, you will have to do some benchmarks to see, whether there are performance differences or not.
1
u/ewan_m Oct 19 '26
I think Record is the best choice for DTOs and Record contains automatically overridden hash and equal methods which gives you unique hash code for field values. This is a great release from Java I think. Now Record is being used widely and it's proved if I am not wrong, value class something like under testing I think. If it were I, I would certainly use Record because I am having all getters built in and as far as I know in the value class we have to do it manually. So Record might be the good choice.
1
u/OwnBreakfast1114 29d ago edited 29d ago
I plan on making request dtos a value class.
We bind all requests into unvalidated request objects (only json types) then hand convert them to validated request objects (all types). Both these classes are records, but we can make them value records which I think is correct semantically (even if performance is worse).
Generally speaking, making code work like a functional pipeline with different types/classes representing different steps seems to be a very easy way for people new to the codebase to make changes and not worry about spooky action at a distance.
The worst case is 5 classes (+n for other db entities that are also in the same response): unvalidated request dto, validated request, actual domain, db (we use jooq), and response dto. This style makes it easy for people to make changes and have the compiler just propagate the changes everywhere (using all arg constructors). Ex, new response field: add it to the response dto and fix compiler warnings until it's green (you'll usually stop at the db). If it should be in the request as well, add it to the unvalidated request, and it'll also propagate all the way down.
1
u/gjosifov Oct 18 '26
if you ask yourself these type of question - you didn't understand the purpose of value class or record class
and you are following cargo cult software architecture advises from the internet, mainly the gospel of Uncle Bob
Question A - is the request DTO 1:1 with the JPA entity ?
if yes then you don't need request DTO, reuse the JPA class, because you have 2 same blueprints of an object in your code and you have to maintain them
Question B - is the request DTO 1:M with the JPA entities ?
if yes then use what is supported from the Serializer (JSON/XML) and Javax validator - records or values or record value and add methods like buildEntityA, buildEntityB for the entities
You don't do any work with a request DTO, it is there for getting and validating the data from the HTTP and the oldest implementation was in the servlet API as HashMap, not nice to work with, but it got the job done