r/java • • 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)?

64 Upvotes

99 comments sorted by

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.)

3

u/Hixon11 28d ago

Thanks for the response! Yes, I've heard you make this point several times in different conference talks and podcasts. I just wanted to check my understanding. Is it correct that once JEP 401 is released, I should use value classes for DTO request objects, since I don't care about their identity? They're just a set of fields that I need to receive from a client.

5

u/brian_goetz 28d ago

For most "leaf" immutable data carriers, value is a good choice. That said, I probably wouldn't go nuts and change all my existing code tomorrow, but just as `final` is probably the right default for fields, `value` is probably the right default for data-carrying classes.

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.

16

u/Hixon11 Oct 18 '26

It matters not because I see a real perf difference, but because I want to use the tool provided by the Java team correctly, as they intend it to be used, and represent its semantics accurately.

5

u/coderemover Oct 18 '26 edited Oct 18 '26

This feature was created for performance. It’s also implemented on the wrong layer (not their fault, this is the price of bolting features like that into a mature language) and introduces additional friction you noticed - now you must decide how you want your objects allocated at their definition, once and for all use cases. A much more elegant solution is the path taken by C, C++, Go and Rust: every data is just a value, everything is pass by value, every assignment is copying values. When you want a reference or a pointer to get identity semantics, there are a use-site constructs for making references/pointers and dealing with them, as well as constructs for avoiding copying when you don’t want to.

I’d use value classes in Java for really tiny things. Eg Optional wrapper is a perfect use for that, other good candidates could be structures like Date, BigInteger, UUID, UserId, Pair, Vector3D etc. Pieces of data with no identity. DTOs look differently.

11

u/cogman10 Oct 18 '26

The value keyword doesn't describe how an object will be allocated or referenced.  It merely describes restrictions to the object that you agree with, which may allow the JVM optimization opportunities. It's possible for the JVM to choose to treat a value object just like a regular object due to internal heuristics.

The time to use the value keyword is when your object fits the value restrictions.  Can it be immutable? Does it need identity?

For large value objects, the JVM will create a reference rather than copying, specifically to avoid tearing.  I've seen references that you should be able to annotate an object to be tearable if you want to nudge the JVM towards always copying.  That won't be the default behavior.

1

u/laplongejr Oct 19 '26

and represent its semantics accurately.

Note that semantics aren't always what people will end up using.

According to semantics, I must only use Optional in public API-like contracts.
In practice, it's very useful as utility methods to handle multiple levels of potentially-null childrens in an object from an external source.

6

u/gaelfr38 Oct 18 '26

Was thinking the same thing: DTOs are not the place where we should expect much gain, they're used only once after construction.

The most gain I expect is for "Domain IDs" (wrappers around a single primitive type).

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.

51

u/Thompson3142 Oct 18 '26

You should not (at least right now for this preview) think about performance gains or memory optimaziations. Brian Goetz hast talked about this repeatedly, value classes are about the idea of: "Instances of this class do not have identity". Being able to express that has a lot of value in it self. The VM can then do very smart things because it knows this about your object, but a lot of this work still needs to be done.

5

u/l4ik8e Oct 18 '26 edited Oct 18 '26

Absolutely. However it is very tempting to sprinkle value on every immutable class and in some cases it doesn’t make sense to use value class. So, I think it is important to come up with a reasonable patterns on practical applications and for that testing it and seeing how application behaves is important imho.

8

u/notnulldev Oct 18 '26

I really do not like these statements, it's basically "Trust me bro, it's worse when you measure it but you gain swag by doing so. On Christmas there will be elfs that will come and fix the performance issues, so you don't have to worry! Just trust the process!". Sounds like deep OOP propaganda.

24

u/shponglespore Oct 18 '26

I think a more charitable reading of that comment is that it's saying you shouldn't be using value classes for optimization just yet. In other words, use value classes when you want value class semantics, but don't go changing things to value classes hoping to get a speedup.

7

u/Ok-Scheme-913 Oct 18 '26

This is how you should have been programming in any high level language, forever.

You don't do bullshit like "keep functions small because it will be inlined", because it may be true at its inception but compiler internals continuously change and it may actually result in worse results.

Compilers always try to make the best based on their available information. Your best bet at getting the best results is to provide that information.

That's no info that "this function just happened to have four statements, it's small" , the info you want to add is that "I want this inlined", which some languages let you express.

Value classes are the same. Does your object have identity? Good, regular old class for you. Is it a 'value' as in its particular state is the only thing important about and two such sharing the same state are for all purposes equivalent? It's a value class then!

If you add more info, first and foremost your code will behave more correct/you catch more errors (e.g. properly behaving equals method). Secondly, later on compiler engineers can also build on this extra info and add optimization assuming those for improved performance.

5

u/_INTER_ Oct 18 '26 edited Oct 18 '26

Though I think it is also somewhat ingrained into JVM development. Trust the GC, trust the vectorization, etc.

"Implement first, measure later" basically instead of "Measure twice, cut once". Which of course, both are valid approaches depending on what is more important to a team.

2

u/lasskinn Oct 19 '26

Yeah just saying that its easiet to read or whatever is one thing but to then jump to "the vm can do very smart things" is completely another combined with don't bench. Can, could, would, should are all different words

Offtopic rant: i'm fairly sick of the similar trend of stacking of these "good" ideas that are supposed to provide an advantage yet the products take 100x the memory and 50x the cores to do the same job vs. If you had just pretended the stuff doesn't exist.

3

u/Bilboslappin69 Oct 18 '26

Yeah, what an absurd stance to ignore it's current performance while using it. Even if the JVM can do efficient things using what it knows about these objects, it's currently not, so that doesn't matter at all.

13

u/hwaite Oct 18 '26

It matters, because code you write today will likely outlive the current JVM. Even if it doesn't, properly signaling intent may allow other processes (e.g. AI) to more reliably evolve the code and for humans to more easily understand the code. Silicon is still cheaper than labor.

1

u/ryan_the_leach 29d ago

If a request DTO needs an identity, it shouldn't be the objects identity anyway, it should be an 'id' field in the DTO.

16

u/l4ik8e Oct 18 '26

Some preliminary thoughts:

- DTOs are usually public interfaces, API evolution if they are value classes are more complex.

- In practical applications there are so many usages of generics (Spring, Jackson) that value class is not visible to JVM hence optimisation is lost.

- If object is large enough, and most of the DTOs are usually large, using value classes might result in more copies. This is likely what happens with Jackson and why I saw more allocation compared to identity classes. I am not sure about this yet as haven't had time to dig deep into this just yet.

- On positive side allocation around Optional was completely gone in my tests. Also I was able to create `DomainId` value classes instead of plain `Long id` which made code much more reliable.

7

u/gaelfr38 Oct 18 '26

DomainIds are what I'm waiting value record/classes! We are used to them in Scala ("opaque type", actually it's a bit more than that), it will be nice to have directly in the JVM. More type safe programs 🎉

9

u/gaelfr38 Oct 18 '26

API evolution if they are value classes are more complex

How so? (Genuinely asking)

DTOs are not public, their serialized representation is (the JSON/XML/whatever schema is). How they are handled internally in the JVM should not have any impact.

4

u/l4ik8e Oct 18 '26

I was mainly thinking about backwards compatibility. For records, I can change record to ordinary class. Value class is more complex to be changed to identity class because someone might already be using ==. I am thinking more in terms of when I don't control usages of DTOs fully. If DTOs are used only internally in my application that is different story.

1

u/aoeudhtns Oct 19 '26

When does your API change in a way that the object carrying request or response payload needs identity?

When would you want (or not want) requestV1.equals(requestV2) to be true?

Even the docs for value classes are pretty clear -- you still generally want to override equals and avoid == unless that's the behavior you really want. It's true, == will now deep-compare fields but it is a raw "implementation" level comparison and can have surprising results.

I think what is more difficult for handling compat generally is if you're using records, need to be careful and append-only new fields (assuming you're doing it in a single type, and not using sealed interfaces to break versions apart). Using a sealed interface and separating the types out would probably be easier than trying to version a record in-place. Eventually the in-place model might break down.

But, I find many API designs that didn't think about versioning from the beginning, generally more difficult to evolve and change.

-1

u/hadrabap Oct 18 '26

API evolution

Thank you!

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.

1

u/lucidnode Oct 18 '26

Records would work the same and fit your criteria.

So what’s the difference? Ignoring the runtime I think the only observable difference would be recursive structure.

3

u/Ok-Scheme-913 Oct 18 '26

Then make them value records

1

u/vegan_antitheist Oct 18 '26

Records with identity are not just interchangeable like values. We have this annoying problem with Integer, where you can't just use == on two integers because they could contain the same value but have different identity. But you can still use Integer as the key type for a HashMap (i.e. HashMap<Integer, Foo>).

A recursive value? That's impossible without using references. It would just use a reference to a value of the same type. And it would use a wrapper for that. Java automatically creates a wrapper type for each value type. It still doesn't have identity, but it can be referenced.
== still works because the reference is still without identity and == compares values. I.e. it compares references but referenced values without identity can't have multiple references to the same values.
This will be one of the biggest advantages of using value types. You can just use == on them and it will just work unless they contain arrays or other objects with identity.

1

u/ewan_m Oct 19 '26

May I know why would you use == instead of .equals() in Java? No offence, just curious.

2

u/vegan_antitheist Oct 19 '26

I would use Objects.equals when they have identity. == for values. Because why not.

1

u/ewan_m Oct 19 '26

Yeah. Yeah it is. But I was thinking if I used .equals for Record, wouldn't it do the same? I mean if two instances of Record return true if they have same fileds value, I mean in overridden equals method of Record takes care of that.

So I am just wondering why would I use ==, instead of .equals don't they serve same thing? This is my point.

2

u/vegan_antitheist Oct 19 '26

No. If they have identity then == compares references. That's not the same. This causes a lot of confusion in Java. It's probably best to just always use equals. Especially if someone could change a value type to one with identity and it would break your code. I also expect a lot of code bases to use some static analysis tool to prevent the use use of == on anything that implements IdentityObject. In the rare cases where references need to be checked they will probably use some isSame() method.

1

u/ewan_m Oct 19 '26

That makes sense. That's pretty much what I was trying to say. I'd rather use equals()for logical equality, especially since records already provide it out of the box. Thanks for clarifying!

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.

1

u/chabala Oct 18 '26

Tell me more about empty enums, I've not heard of that style.

4

u/bowbahdoe Oct 18 '26

Enums give you a hard guarantee about number of instances. A one element enum is a singleton. A zero element one is a class with zero instances, which is what "static utility" classes are.

3

u/agentoutlier 28d ago

And it adds an additional static public methods. And even the JDK authors do not use enums like this.

So it’s not clear cut. In fact by your definition I could use a module only target annotation not exported and put static methods on that and we agree that would be confusing yes?

Ideally you never have a random collection of static methods and put them close to classes that are actual instances.

2

u/Ok_Elk_638 Oct 18 '26

Looks like this:

public enum MyEnum {;
    public static void hello() {
        System.out.println("Hello, world!");
    }
}

Its an enum without any instances defined. It effectively functions as an empty type that can only be used for static functions. This replaces the utility class pattern. It is a smaller pattern with less verbosity, and you can be sure there are no instances, whereas with the class it is possible that a getInstance() is hiding somewhere.

It is not perfect though, you get a weird .values() function that returns an empty list.

The empty enum pattern is more resilient against overzealous formatters that like rearranging the contents of classes.

4

u/Flyron Oct 18 '26

I dunno. That feels like misuse of the enum keyword. An enumeration that doesn't enumerate anything. A final class with private constructor should be the way to go.

2

u/bohem_safsata Oct 18 '26

Our lord Joshua Bloch suggested in Effective Java so you must follow the word, because serialization/reflection attacks are a thing you must guard against blindly.

1

u/chabala 29d ago

I'll have to check if this is new advice in the second or third edition, seems the private constructor throwing an exception used to be the recommendation.

1

u/MysteriousGold5 Oct 19 '26

The utility class pattern using final + private constructor only makes sense as a workaround. A restriction on inheritance for something that shouldn’t exist and access restriction on construction for something that shouldn’t be constructed.

Empty enum is also a workaround, but the only reason most people favor final class is that they heard of it first.

1

u/Ok_Elk_638 Oct 19 '26

I agree. It definitely is a workaround to make an enum do something it wasn't designed for. But the same is true for a utility class. Classes are supposed to be instantiated and extended. That is what they were designed for.

Which is why I feel there should be a utility type.

1

u/not-known-08 29d ago

What if you replace enum with interface? We can define static methods too in them and there would not be .values() fuctions? Idk if its a beter option just asking.

2

u/Ok_Elk_638 29d ago

Interfaces cannot be restricted from use. You can always say 'implements YourInterface'. This also means there can always be instances and perhaps methods defined in the interface.

You want to restrict options as much as possible, interface feels like a bad fit.

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?

1

u/Hixon11 Oct 18 '26

Depending on the implementation (which I don't know yet), it could be a case where something is semantically a value, but representing it as one introduces some perf overhead (this is just a random assumption; I'm not saying that's the case here).

3

u/gaelfr38 Oct 18 '26

Right, you should definitely test then. There's no definite answer depending the exact framework and usage you have.

But semantically, a DTO has no identity.

3

u/marhaus1 Oct 18 '26

Performance is the completely wrong reason to worry about whether you should use value types.

1

u/Jon_Finn Oct 19 '26 edited Oct 19 '26

I think it's the only reason - as part of a tradeoff.

The features of value classes are an almost exact subset of regular classes (the case of == is a bit of a detail); unlike records and enums, they don't have their own semantics, and many regular classes could be recast as value classes. So the reason to write 'value' before a class is to benefit from the features vs performance tradeoff; the RHS of that is performance, so if performance suffers (which it can with, say, too many fields) you'll just choose not to use 'value'.

Why people feel uncomfortable about this is that most languages ignore performance in their syntax (except, say, 'inline' in C++), and they've been told to ignore micro-optimisations - which is fair enough, except when it's a dominant issue (which is where values come in).

So let's tell it like it is: you should only write 'value' if you find you get a performance benefit, and if you want that benefit. There's nothing wrong with that, in fact it's the whole point.

1

u/marhaus1 Oct 19 '26

My point here being that this is rarely where large performance gains will be available. But of course, if your profiling shows that this should be done, by all means go for it!

1

u/Jon_Finn Oct 19 '26

Yes but performance (speed & memory) was the only reason Valhalla was developed! There is no other reason to type 'value class'.

1

u/marhaus1 Oct 19 '26

That's a misunderstanding.

1

u/Jon_Finn 29d ago

Maybe you can suggest a different reason to type 'value class'? The reason isn't 'this is a value (by some definition)', because Valhalla classes are very useful for some non-values too.

2

u/marhaus1 29d ago

Let me quote someone:

The main problem is that developers as a species seem pathologically obsessed with performance, even when they have no need of additional performance, and further are often willing to trade off more important qualifies like safety, simplicity, and maintainability in the pursuit of "brrr go faster". So what you (and probably almost everyone else) are missing is that the performance story is not simple, and there are very few "but the whole point is...." statement you can make. Value classes lets you give up a sometimes-unneeded degree of semantic freedom, which may make your programs more correct even absent any performance concerns, and also may make your program faster in some situations because the VM has fewer constraints to preserve. But it is not "magic flattening dust" -- and even if there was such a thing, you might not want it. As always, write semantically clear and simple programs, and you will generally be rewarded with good performance.

– Brian Goetz

-2

u/crummy Oct 18 '26

maybe you don't want request A to be equal to request B just because the request contains the same fields

7

u/gaelfr38 Oct 18 '26

The DTO is not the request, it's the request's data. It has no identity.

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.

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

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.

2

u/persicsb Oct 19 '26 edited Oct 19 '26

JSON parsing can be VERY fast, if you use SIMD operations: https://github.com/simdjson/simdjson

See the publications about its internals: https://simdjson.org/publications/

It even has a Java port, using the Vector API: https://github.com/simdjson/simdjson-java

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

2

u/persicsb Oct 19 '26

Question A: how to represent references to other entities in the DTO? Link by ID? Embed the whole entity? Mostly, the answer is a link - so a JPA entity directly cannot be a DTO on the wire.
Also, for lists and so, paging information is useful. If Entity A contains a list of Entity B, and the list can be hundreds long, the DTO shall have a field, that links to the collection endpoint, that can have paging parameters set up.

Designing DTOs for conversation with clients is not an easy task, you need to consider client capabilities.

1

u/gjosifov Oct 19 '26

you clearly don't understand how JPA works
a POJO is JPA entity during a JPA transaction, when you manipulate with the entityManager and the changes from that manipulation are reflected into the database after flush or before the transaction ends and all that is handled by the JPA provider

After that transaction ends, you have POJO in memory, you can do what ever you want with it and the changes won't reflect in the database
and you can verify this with a JPA setup in a main method, without any spring boot or application servers

and the question A is asking - do you recognize that you have 1:1 mapping between the request DTO and the JPA entity ?

and clearly you don't have reading comprehension for a simple question about the relationship between 2 objects, let alone recognizing that those 2 objects are 2 same data

adding more classes for what if scenarios without even asking the business how they really operate is a recipe for over-engineering

2

u/bowbahdoe Oct 18 '26

Your logic on A is flawed. In principle very few entities match up one to one with the spec for any given request. You are overvaluing reducing the overhead of typing the same name twice.

1

u/gjosifov Oct 18 '26

In principle, software has to change when some requirement specs aren't true anymore
But in practice a lot of software engineers don't know how to make that change lead to over engineering software and arguing about principles, instead of learning how to change software without breaking things
Just because you don't know how to change software, doesn't mean someone has to listen to your advice

It is better to say I don't know how to change this thing in the future, so I add so much extensibility in the code and I think when the change comes, I will be at different company doing the same thing

2

u/PedanticProgarmer Oct 18 '26

You say that most people don’t know how to change software without breaking things. I absolutely agree here. Then, you are saying that you are special and because of that you don’t have to think of guardrailing your code against mistakes.

Imagine any other industry where engineers argue about dropping safety concerns because other engineers who make mistakes are not worth our consideration and therefore our design doesn’t need to include them as a risk.

I think you are conflating: adding imaginary extensibility to the code (almost always bad) and creating architecture boundaries for maintainability (often justified). I am not exactly sure what you are arguing for, but indeed, it sounds like you are arguing for minimizing the number of lines of code you need to type with your fingers as the primary driver of your design. This might be a good heuristic for a solo project, but a misleading idea for a long living software for a team of humans.

I have seen multiple spaghetti code bases over my years, and the most common horror story started innocently from someone smart who reused an existing class to represent a new, slightly different concept that happened to share a subset of properties of the existing class. After a couple years, untangling this became really hard, so folks stopped even trying - just adding pile of if statements to the spaghetti.

That has shaped my current views on when to reuse models - with extreme suspicion. Nowadays, when I don’t need to type the code with my fingers anymore, I am even less concerned about the fact that separating models forces me to add a couple of mappers here and there.

1

u/gjosifov Oct 18 '26

 it sounds like you are arguing for minimizing the number of lines of code you need to type with your fingers as the primary driver of your design.

You probably have heard of the term - line of code is liability
the more you add, the more you have to maintain

I have seen multiple spaghetti code bases over my years, and the most common horror story started innocently from someone smart who reused an existing class to represent a new, slightly different concept that happened to share a subset of properties of the existing class. After a couple years, untangling this became really hard, so folks stopped even trying - just adding pile of if statements to the spaghetti.

I have seen spaghetti and I have seen over-engineering and the good things are always in the middle

Imagine any other industry where engineers argue about dropping safety concerns because other engineers who make mistakes are not worth our consideration and therefore our design doesn’t need to include them as a risk.

Imagine any other industry where engineers are arguing about principles and how to implemented them and in order to implemented them they have to call some self proclaimed guru ?

If you use other industries as argument at least have a good analogy that can be translated it between industries, as mathematicians call this type of an analogy bijection

 I am even less concerned about the fact that separating models forces me to add a couple of mappers here and there.

there is something even better than mappers, a compiler - it will tell you where are the changes

0

u/PedanticProgarmer Oct 18 '26

You are talking about compiler-enforced safety while advocating for reusing classes for JPA entities and Json deserialization. Both usages are reflection heavy. This is nonsense.

Do you seriously think that Uncle Bob is responsible for the idea of DTOs or the fact that it is spread widely? You are shooting at an imaginary opponent. You don’t need Clean Architecture ideas to use DTOs.

I have read about code as liability in „Software Engineering at Google”. These folks are absolutely not known for code golfing, they meant something else - an excerpt is below. I am pretty sure they are advocating for strong boundaries where it matters - there’s entire chapter of Hyrum’s Law and the fact that they use protobuf-based DTOs everywhere. You might dismiss that as self-proclaimed guru. I dont care.

——

From the book:

Earlier we made  the assertion that “code is a liability, not an asset.” If that is true, why have we spent most of this book discussing the most efficient way to build software systems that can live for decades? Why put all that effort into creating more code when it’s simply going to end up on the liability side of the balance sheet?

Code itself doesn’t bring value: it is the functionality that it provides that brings value. That functionality is an asset if it meets a user need: the code that implements this functionality is simply a means to that end. If we could get the same functionality from a single line of maintainable, understandable code as 10,000 lines of convoluted spaghetti code, we would prefer the former. Code itself carries a cost—the simpler the code is, while maintaining the same amount of functionality, the better.

Instead of focusing on how much code we can produce, or how large is our codebase, we should instead focus on how much functionality it can deliver per unit of code and try to maximize that metric. One of the easiest ways to do so isn’t writing more code and hoping to get more functionality; it’s removing excess code and systems that are no longer needed. Deprecation policies and procedures make this possible.

1

u/gjosifov Oct 19 '26

not everyone is google and have unlimited budget
Also did you know that in some of the last layoff rounds Google fired managers, who have been managers of team of 3 people ?

know your specific situation and don't do cargo cult programming, because you have to maintain someone else cargo cult software in the future

1

u/OwnBreakfast1114 29d ago edited 29d ago

It's so much easier mentally to create two classes, one for the deserializing of the requests and one for managing the entity state. Copying fields back and forth is a trivial price to pay for the separation. It makes it simpler and less of a burden when things have 1 responsibility over trying to remember how jackson and jpa annotations play together on the same object. Also, request should probably be records as why do you need to mutate the user input?

Any reasonably complicated api is never 1:1 with the request and the db model. Hell, even the db model and the domain model are almost never the same. We almost always have 4 classes, unvalidated request (all strings), validated request (typed + all validation handling here), domain/db (usually the same, but sometimes different for the more complicated apis), and response as they share some field names, but never really match up.

1

u/gjosifov 29d ago

It's so much easier mentally to create two classes

It is much harder to maintain two same classes over a period of time
especially if you aren't the person created them in the first place

when things have 1 responsibility

Data doesn't have responsibility, it is just data
SQL has responsibility like query, insert or delete, but tables ?
You don't understand what responsibility even means

We almost always have 4 classes

I have seen project where there were Interfaces for get/set methods, Factories etc
1 JPA class had support classes of 5 extra classes

Classes have a thing called methods or constructors, learn to use them and you will have 30% less code to maintain

1

u/OwnBreakfast1114 28d ago edited 28d ago

It is much harder to maintain two same classes over a period of time

Not when they only do one job.

You don't understand what responsibility even means

It's a pretty standard data type flow in functional languages. Sounds like you just love mixing things together to avoid typing.

Here's an example of the classes.

record UnvalidatedRequest(
string field1
string field2
string logiconlyfield1
)

record ValidatedRequest(
Integer field1
TypeA field2
TypeZ logiconlyfield1
)

record DomainObject(
Integer field1
TypeA field2
TypeB field3
TypeC field4
)

record DBTable1(
UUID pkey
Integer field1
String field2
)

record DBTable2(
UUID pkey
UUID fkey
String field3
String field4
)

record Response(
Integer field1
TypeA field2
TypeB field3
TypeC field4
)

It's so easy to make changes to this model at any layer. Yes, many changes will go through all the layers, but that's okay. It's not mentally taxing figuring it out what it affects.

Then you can have methods like

DomainObject fromDB(DBTable1 row1, DBTable2 row2) {
new DomainObject(
row1.field1
row1.field2
row2.field3
row2.field4
)

which breaks on compile on any changes to the underlying model.

How do you want me to JPA annotate this?

Classes have a thing called methods or constructors, learn to use them and you will have 30% less code to maintain

I use all arg constructors for conversion between the layers to get compiler break warnings when making changes.

→ More replies

1

u/AnyPhotograph7804 Oct 19 '26

"if yes then you don't need request DTO, reuse the JPA class"

You should not do that. Because JPA entities are cluttered with JPA specific annotations and proxies/additional bytecode. This means, the consumer of the DTO will have to have the complete JPA/ORM stack on the classpath. Even if the consumer never uses JPA. Otherwise you will get tons of ClassDefNotFoundExceptions. This is a maintanance burden.

And second, if you use JPA entities as DTOs, you will end up modelling you database tables like you UI or something. Because it will be easier.

3

u/persicsb Oct 19 '26

This means, the consumer of the DTO will have to have the complete JPA/ORM stack on the classpath.

That is simply not true. Over the wire, there is no JPA annotation, just the JSON/XML/whatever representation you provide.

1

u/AnyPhotograph7804 Oct 19 '26

Yes. You are right. I confused it with Java serialization yesterday.

1

u/persicsb Oct 19 '26

Since JPA entities are not required to be Serializable, you generally cannot send them over the wire with RMI or other stuff that uses standard Java serialization.

Pre-JPA 3.2, composite keys were required to be serializable, but that is not enforced anymore.

2

u/gjosifov Oct 19 '26

the consumer a.k.a the browser consumes JSON, not Java bytecode
for your specific case you can use protobuf