DDD and the UI layer
Hi everyone,
I wanted to get some insight from those that write server code in a DDD style and use that code on the front end. I like the concept of the front and backend sharing validation, but my backend has been written in such a way that it accepts json, validates the json, and turns it into domain types. For example:
type NonEmptyString100 = private NonEmptyString100 of string
Specifies a string that cannot be empty and max 100 characters.
I wanted to share this on the front end, but I have run into issues where the domain types do not translate well into the corresponding datatypes without constantly unwrapping and rewrapping. For example, a textbox value.
Is this an easy fix or should I separate the validation from the translation steps?
Posted Sep 3, 2020, 1:04 AM UTC
There's several good reasons to duplicate your types in two versions:
One reason is, as you've found, to avoid problems with mapping and unmapping to view models or JSON payloads.
Another, just as big, is that you are able to tweak and update a single domain model without causing breaking changes in your DTO. A third, related to the second, is that you can now support versioned APIs by adding new versions of DTOs for each new endpoint, while your actual code works with a single up-to-date domain model.
And a fourth is that you now have the freedom to decouple the message types from the model types, so you can design free RPC calls instead of sticking to a REST-ish model where you send updated entities.
Once you have the two sets of types, if you are returning a DTO as an output, you just need a
(model -> dto)function. If you're taking it in as an input, you want a(dto -> result<model, validationError list>).There are two situations where I would consider not duplicating the type:
When you you're going full-stack F#, be it with Fable, Websharper, Bolero, or whatnot. In that case you can happily reuse the same types, being aware that your frontend and backend will be very tightly coupled and should be deployed as a single entity and you will not be able to call the same endpoints from multiple frontends (eg. web app + native client) unless they are all written in F#.
When you're going full-in on your web framework's native validation tools - in the case of ASP.NET Core, you're supposed to have dumb unsafe C#-style classes, and then decorate then with validation attributes such as
[<MaxLength 100>]. This has a significant upside in that you don't need to actually write the validation code, the framework will automatically return a pretty good HTTP 400 error message saying stuff like 'The name field should not be longer than 100 characters'.