📎 Webclip
Don't Parse, Use Parsing Objects
The article argues that deserialization should be handled by objects rather than by DTOs that are parsed in an entry point. In the example, the library receives a JSON request for a book, and the parsing logic is moved into a JsonBook object that implements Book.
Reading notes#
- The traditional DTO approach serializes objects to JSON on the way out and deserializes them on the way back, but the article says this is the wrong pattern.
- Serialization should be replaced by printers, and deserialization should be done by objects.
- In the first example, the HTTP entry point reads multipart form data, parses JSON, creates a
BookDTO, sets the ISBN, and callslibrary.register(book). - That approach is not reusable, because the same HTTP processing and JSON parsing would need to be rewritten elsewhere.
- Error handling and validation are not reusable there either, so adding them to that method would force duplication.
- The code is also procedural and has temporal coupling between method calls.
- A better design hides parsing inside a
JsonBookclass that stores the JSON body and returns the ISBN through itsisbn()method. - With that design, the REST entry point only constructs
new JsonBook(...)and passes it tolibrary.register(...). - The article gives
RqUseras another example from the author’s projects. - When a primitive like
Stringis afinalclass rather than an interface, the article uses a class that implementsScalar<String>and returns the parsed value fromvalue(). - These examples are presented as support for the principle of parsing objects.
