instantiating a domain object from form input - webforms

In DDD, your domain object's properties are mostly readonly from the outside. Now, in MVC, you'll typically get the object provided to you from the view or repository, but how do you go about this in Webforms, where you read the form inputs manually and apply them to the domain object? Do you create a DTO and give the domain object a Create method that takes the DTO?

The common pattern for recording an action or activity in a domain model, is to model the action as an object associated with the thing, people and places it interacts with.
So by example, if one had Orders associated with a Product, one would typically create the Order via an Order method on the applicable product. Data representing the Order captured via the UI would be passed to that Order method.
This represents the simple case for illustration purposes.

Do you create a DTO and give the domain object a Create method that takes the DTO?
No, you will typically have a piece in the middle, a message handler which is responsible for taking the DTO and converting it to values recognized by the domain. The domain objects have command methods that are used to update the state of the model.
So something like
Receive the DTO
Lookup the appropriate handler for that DTO
Parse the DTO, creating the value types recognized by the domain
Load the target aggregate from the repository
Invoke the command on the target, passing domain value types as arguments.
"Input validation" typically happens in step 3. "Business validation" typically happens on step 5.

A good approach is to make your domain entities always valid, always consistent. How you make them consistent right from creation is simply through the entity's constructor or a Factory that will check that the provided input is good enough to construct a valid entity.
Do you create a DTO and give the domain object a Create method that
takes the DTO?
The Domain layer doesn't have a dependency to other layers, so you can't reference an external DTO there. Entity constructors and Factories typically take primitive values or value objects (sometimes other entities) as an input, not DTO's.

Related

What is the best way to write appropriate validations for domain models in DDD?

I've heard about different ways to write validation for domain models, So I want to know which of them is better in the domain-driven-design.
Some people say that it's better to validate the domain model's data before initializing it (it means that validations should be run on the related DTOs).
Some people say that it's better to validate the domain model's data after initializing it (it means that validations should be run on the initialized entity or domain model).
Also, some people say that all the validations should be run inside of the entity (exactly in setters or constructors)
Indeed, I was used to writing a combination of the above validations, but now I'm not sure about that. Which of them is common and basically more sensible?
In domain driven design, what you are most likely to see are "value objects" that guarantee certain constraints are met during initialization, therefore in the constructor of the value object itself. Since values are (by convention) immutable over their lifetime, you wouldn't normally include setters in their interface.
DTOs serve a different purpose, but are mechanically similar to value objects in many ways. So you might see validation in the DTO in addition to validation within the domain model.
You don't normally have value validation in your entities. An entity is typically holds references to values (which validate themselves) or other local entities (validated elsewhere), so checking that the references are correct is in bounds (ie, check for null).

Clean Architecture - Where does mapping of DTO to business model should happen?

I have a DTO that's managed by a Repository and in the end I want to map this DTO to a different type of object that's used by the Presentation layer.
Should the mapping happen in the Repository or in the domain layer? ( Use case/ Interactor)
In clean architecture the repository returns entities which are "used" bei the Interactors to implement the business rules. The Interactors return "response models" (DTOs) which are used by the presenters to generate "view models" which are used by the views to show results to the users.
Depending on the responsibility of ur "different type of object" the mapping would be in the Interactor or presenter.
U can find more details about Interactors and presenters in my blog post here: https://plainionist.github.io/Implementing-Clean-Architecture-Controller-Presenter/
I think the term DTO is a little too vague to answer this question. It really depends on what the purpose of the transformation is.
For example, let's assume we have some kind of system that has a Book object in its entities (in the domain layer). The book object returned by the repositories may have a field named pendingDelete because we delete books in a background task in batches. This field is needed by the domain layer but not externally and so, in the use case layer, we transform the book object into another object (maybe by casting to an interface or maybe creating a whole new object) that does not have this field. This meets the definition of a DTO in my brain and this mapping would happen in the domain layer.
Alternatively, lets now consider that we need to transform that object into a different object that has been decorated with various annotations/metadata that instruct how to serialize the object into XML or JSON. This also meets the definition of a DTO but this mapping would happen outside of the domain layer.
In the first example, we are using the DTO to control the interface to our inner layers and so we do that mapping in the inner layers. In the second example we are using the DTO to control the interface to our outer layers and so we do that mapping in the outer layers.
Usecase makes use of plugins. Plugins are abstraction over libraries (Gateway).
So in this case, a library (native or third party) will have to make an API call and get the json response, then convert it as a DTO object and hand it over to the usecase with the callback method. Then usecase can hand it over to presenter which will then convert it to respective view model.

Parameter validation vs property validation

Most (almost all?) validation frameworks are based on reading object's property value and checking if it obeys validation rules.
Do we really need it?
If we pass valid parameters into object's constructor, property setters and other methods, object seems to be perfectly valid, and property value checks are not needed!
Isn't it better to validate parameters instead of properties?
What validation frameworks can be used to validate parameters before passing them into an object?
Update
I'm considering situation where client invokes service method and passes some data. Service method must check data, create / load domain objects, do business logic and persist changes.
It seems that most of the time data is passed by means of data transfer objects. And property validation is used because DTO can be validated only after it has been created by network infrastructure.
This question can spread out into wider topic. First, let's see what Martin Fowler has said:
One copy of data lies in the database itself. This copy is the lasting
record of the data, so I call it the record state.
A further copy lies inside in-memory Record Sets within the application. This data
was only relevant for one particular session between the application
and the database, so I call it session state.
The final copy lies
inside the GUI components themselves. This, strictly, is the data they
see on the screen, hence I call it the screen state.
Now I assume you are talking about validation at session state, whether it is better to validate the object property or validate the parameter. It depends. First, it depends on whether you use Anemic or Rich Domain Model. If you use anemic domain model, it will clear that the validation logic will reside at other class.
Second, it depends on what type of object do you build. An Framework / operation /utility object need to have validation against object property. e.g: C#'s FileStream object, in which the stream class need to have valid property of either file path, memory pointer, file access mode, etc. You wouldn't want every developer that use the utility to validate the input beforehand or it will crash in one operation, and giving wrong error message instead of fail fast.
Third, you need to consider that "parameter can come in many sources / forms", while "class / object property only has 1 definition". You need to place the parameter validation at every input source, while object property validation only need to be defined once. But you also need to understand the object's state. An object can be valid in some state (draft mode) and not in other state (submission mode).
Of course you can also add validation into other state level as well, such as database (record state) or UI (screen state), but it also have different pros/cons.
What validation frameworks can be used to validate parameters before passing them into an object?
C#'s ASP.Net MVC can do one kind of parameter validation (for data type) before constructing into an object, at controller level.
Conclusion
It depends entirely on what architecture and kind of object you want to make.
In my experience such validations were done when dealing with complex validation rules and Parameter object. Since we need to keep the Separation of concerns - the validation logic is not in the object itself. That's why - yes we
we really need it
What is more interesting - why construct expensive objects and later validate them.

How do I represent multiple DTOs for a domain object in .NET Web API?

I'm writing a set of REST services and have come upon a problem that I'm sure has an appropriate solution/pattern that's just eluding me.
For instance /api/People/1 will return a serialized representation of PersonDto (which is a pared down representation of the Person domain object created by Entity Framework. I'm using AutoMapper to hydrate PersonDto.
However a second controller (say, /api/Classes/) is going to return different complex object, which may contain one or more Persons, however I want to represent each person in a different way than simply using an existing PersonDto (e.g. I might require more or less fields).
Do I need to define a ClassPersonDto? I'm not sure what the "proper" thing is to do here.
If the model of "person" being passed back in "Classes" is different then the "PersonDto" model, then yes, create a different model. You don't need to, but it's almost always better to keep your classes, including entities, as specific as possible.

Validation with DDD in SOA application using IoC

In my service facade layer, I have a service class with a method/operation that accepts a DTO (data contract) object. AutoMapper is used to map this DTO into an instance of my domain object to apply any changes. The request is passed onto my domain service which does the actual work. Here's what the method might look like:
public EntityContract AddEntity(EntityContract requestContract)
{
var entity = Mapper.Map<EntityContract, Entity>(requestContract);
var updatedEntity = Service.AddEntity(entity);
var responseContract = Mapper.Map<Entity, EntityContract>(updatedEntity);
return responseContract;
}
The Service and Mapper properties are set using constructor injection with Unity as the IoC container.
In performing the operation, the domain service makes changes to the entity then uses a repository to persist the changes like:
public Entity AddEntity(Entity entity)
{
// Make changes to entity
Repository.Add(entity);
// Prepare return value
}
The Repository is also set using constructor injection.
The issue is that the data becomes immediately available to other clients once it has been persisted so I have to ensure that no invalid data is persisted. I've read the "blue book" of DDD (Evans) as well as Nilsson and am not clear what approach to validation I should take.
If my goal is to prevent the entity from entering an invalid state, should I validate entityContract in my service method to ensure all rules are satisfied before ever passing the request on to my domain service? I hesitate to do so because it seems like I'm breaking encapsulation having these rules defined in the service facade.
The reason we are using a thin facade layer delegating to domain services is that we are exposing course-grained interfaces in our API but support reuse via composition of the fine-grained domain services. Keeping in mind that multiple facade services may be calling the same domain service method, perhaps delegating these rules into the domain service would be better so we know every use is validated. Or should I validate in both places?
I could also put guards in the property setters that prevent unacceptable values from ever putting the entity into an invalid state. This would mean that AutoMapper would fail when trying to map an invalid value. However, it doesn't help when no value is mapped.
I still can't get past the thinking that these rules are part of the entity's behavior and determining if the object is valid should be encapsulated within the entity. Is this wrong?
So first I need to determine when and where I perform these validation checks. Then I need to figure out how to implement with DI so the dependencies are decoupled.
What suggestions can you provide?
I've read the "blue book" of DDD (Evans) as well as Nilsson and am not
clear what approach to validation I should take.
Blue book approaches the problem from a different angle. I think that the term 'Validation' is not used because it is a dangerous overgeneralization. A better approach is to think about object invariants, not validation. Objects (not only in DDD) should enforce their internal invariants themselves. It is not UI or services or contracts or mappers or 'validation frameworks' or anything else that is external to the objects. Invariants are enforced internally. You may find these answers helpfull: 1, 2, 3, 4.
I could also put guards in the property setters that prevent
unacceptable values from ever putting the entity into an invalid
state. This would mean that AutoMapper would fail when trying to map
an invalid value.
You probably should not care about AutoMapper failing or using AutoMapper at all. Domain objects should encapsulate and enforce their internal invariants and throw exception if the attempt to break it is made. It is very simple and you should not compromise the simplicity and expressiveness of your domain objects because of some infrastructural issues. The goal of DDD is not to satisfy AutoMapper's or any other framework's requirements. If the framework does not work with your domain objects don't use it.
You have two types of validation:
Object consistency: is the responsibility of entities. Entities should not allow you to set them to invalid state, dependencies should be enforced, values should be in range. you have to design classes' methods and properties and constructors not to allow invalid state.
Business roles validation: this type of validation requires server processing, like checking id availability, email uniqueness and the so. these types of validations should be processed in server as Validators or Specifications before persistence.

Resources