Parameter validation vs property validation - 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.

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

instantiating a domain object from form input

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.

Should domain entities hold any data format validation?

Taking some ideeas regarding validation from this book , is it really a good practice and proper SoC to put data validation inside domain objects? There he gives example about validating addresses, checking if it is between an interval of chars long, adding a pattern etc. When thinking about validation isn't better to put the validation right when the user asks something from the application , for example in a command object (cqrs) and stop the user if the command is invalid? Also another problem comes with internationalisation , how would handle the patterns for different alphabets? Also another problem comes with duplicate checks, what if the domain objects checks for each invariant of the property (when it can be of mixed type) but the command actually assumes only one single invariatn to be valid ?
Why I am confused is because Eric Evans forewards this book written by Vernon , but i find some design styles innapropriate . So is it better to validate properties format (string lenght, string format etc, like that address example) in the domain or outside the domain ?
There is user input validation (usually input format) and business rules. The input validation makes sense to be done at the entry point (usually a controller and depending on a framework it can be automatically done), there's no benefit in sending invalid data forward for processing.
However, the domain contains most of the input validation rules so it seems you have to choose between keeping the rules inside the Domain or repeating yourself. But you don't have to, because the input validation can be easily encapsulated into value objects (VO) so they are part of the domain but you can still use them outside the domain to validate the input.
That's why it's best to use VO as much as possible , they usually are domain concepts AND they ensure the value is valid. The entity using them simply must refuse a null value.
I don't how you can validate a command, at most you can check if the user or context can create and send that command, but the command itself is just a semantic DTO with the relevant parameters. It's up to the command handler to decide how valid the command is. Also, I don't think a command should assume anything, it' about what to do not, how to do it.
About i18n, IMO the validator must be aware of the current culture so a possible solution is a service which return the pattern for the current culture. This means the validator (I usually implement it as a static method of the VO) will take something like IKnowValidationPatterns as a dependency.

How do I avoid duplicating validation logic between the domain and application layers?

Any given entity in my domain model has several invariants that need be enforced -- a project's name must be at least 5 characters, a certain product must exist to be associated with the project, the due date must not be prior to the current date and time, etc.
Obviously I want the client to be able to display error messages related to validation, but I don't want to constantly maintain the validation rules between several different layers of the program -- for example, in the widget, the controller, the application service or command object, and the domain. Plus, it would seem that a descriptive error message is presentation-related and not belonging to the domain layer. How can I solve these dilemmas?
I would create specific exceptions related to your expected error conditions. This is standard for Exception handling in general and will help with your issue. For example:
public class ProjectNameNotLongEnoughException : System.Exception
or
public class DueDatePriorToCurrentDateException : System.Exception
Mark these possible exceptions in the xml comments for the methods that may throw them so that applications written against your domain model will know to watch out for these exceptions and will be able to present a message within the presentation of the application. This also allows you to have localized error messages based on the culture without cluttering up your domain model with presentation concerns.
If you choose to perform client-side validation, I'm afraid that you can't have your cake and eat it too. In this case, you may have to duplicate validation logic in order to achieve the desired features while maintaining your architecture.
Hope this helps!
I realise this is an old question, but this may help others in a similar situation.
You have here Behavior and Conditions which you need to encapsulate into your domain model.
For example, the ProjectName having a requirement on a certain length I would suggest should be encapsulated within a ValueObject. It may seem overboard for some, but within our Domain Model we almost always encapsulate native types, especially String, within a ValueObject. This then allows you to roll your validation within the constructor of the ValueObject.
Within the Constructor you can throw an Exception relating to the violation of the parameters passed in. Here is an example of one of our ValueObjects for a ZoneName:
public ZoneName(string name)
{
if (String.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException("Zone Name is required");
}
if (name.Length > 33)
{
throw new ArgumentException("Zone name should be less than 33 characters long");
}
Name = name;
}
Now consumers of that ValueObject can either perform their own validation before calling the constructor, or not, but either way your invariants will be consistent with your model design.
One way we build validation rules within your Domain Model, and then utilise them within your UI is to use the Mediatr module, which uses a One Model In, One Model Out pattern, and allows you to define Validators for each of your Query or Command models. These are defined using FluentValidation. You can then add a Provider to the ModelValidatorProviders within MVC. Take a look at JBogards ContosoUniversity example here https://github.com/jbogard/ContosoUniversity/tree/master/src/ContosoUniversity and look at the DependancyResolution folder, DefaultRegistry.cs.
Your other example of a Product must exist to be linked to a Project. This sounds to me like a Domain Service would be the best option to facilitate the cooperation between 2 bounded contexts? The Domain Service will ensure the invariants remain consistent across the bounded contexts. That Domain Service would not be exposed publically, so you would need an ApplicationService or a CQRS type interface which will take that DomainService as a dependency, allowing the DomainService to perform the operations required. The DomainService should contain the Domain Behavior, whereas the Application Service should just be a facilitator to call that function. Your DomainService would then throw exceptions rather than result in inconsistent or invalid invariants.
You should ultimately end up in a position where you don't have duplicated validation, or at least you never end up with invalid invariants because validation has not been performed at some point, as validation is always handled within your domain model.
While a descriptive error message may seem to pertain to presentation moreso than business, the descriptive error message actually embodies a business rule contained within the domain model -- and when throwing an exception of any kind, it is best practice to pass along some descriptive message. This message can be re-thrown up the layers to ultimately display to the user.
Now, when it comes to preemptive validation (such as a widget allowing the user to only type certain characters or select from a certain range of options) an entity might contain some constants or methods that return a dynamically-produced regular expression which may be utilized by a view model and in turn implemented by the widget.

What is the best way to handle domain-centric validation while providing a rich UI experience?

My company is developing a GUI application that allows users to query a legacy database system and have the results displayed back to them on the screen (the results just come back in a blob of plain-text). I'm struggling with the best way to structure the interaction between the user interface and the domain layer, especially validation of user input.
Basic Use Case
User selects a query to run from a menu in the application.
The application code displays the data entry form for the selected query.
The user enters the parameters for the query. If a field contains invalid data, it is immediately highlighted in red, and its tooltip text is changed to display an error message (i.e. if you are entering a Person query, and you enter a date of birth in the future, for example, the date of birth field will immediately turn red).
When the user clicks Run Query, the application runs a second validation pass; this second validation pass is required in order to run validation checks that involve multiple fields. If the this validation check passes, and all the fields are valid, the query is sent; otherwise, the user is prompted to fix any remaining errors.
My Current Validation/Error Reporting Strategy
Currently, I'm using domain-centric validation, but the overall design seems messy to me and maybe a little too over-engineered. A brief overview of the current design:
Domain layer: I have one class per query. Every query class contains a collection of IQueryField objects that hold the values entered by the user. Each query class implements a common IQueryMessage interface, which defines (among other things) a Validate method. This method is called to enforce message-level validation rules (i.e. rules that must examine the state of multiple fields at once). The IQueryField interface also defines a 'Valdate' method (among other things). This is to support per-field validation rules.
Per-field validation: To handle the per-field validation and error reporting, the data entry code binds each input control to an IQueryField; whenever the user changes the value of a control, it calls the the corresponding IQueryField's Validate method, which in turn fills a Notification object (just a collection of strings at the moment) with any errors detected in the value entered by the user. The user interface code then checks the Notification object and changes the appearance of the user control to indicate an error condition, if necessary.
Message-level validation: When the user tries to send a query, the application calls the Validate method on the IQueryMessage instance associated with the data entry form (at this point, the data binding code has also ensured all the message's fields have been populated from the input controls on the form, and the per-field validation code has been run). If there are any validation errors, the user interface displays them at the top of the form. If there are no errors, the data entry form is closed and the query is serialized and sent over the network.
Is Something Wrong Here?
I feel like something isn't "right" here. I have a few issues with the current design:
I would like the domain-level validation code to indicate the name of any fields that are in error, bur I don't want to hard-code the UI label captions into the domain classes. One possibility I thought of was to have the domain-level Validate methods generate messages with a field placeholder, such as "%s cannot be in the future", and have the UI code fill in the placeholder with the correct label.
The IQueryMessage and IQueryField interfaces both have a method called Validate. I'm thinking this should be extracted into a separate interface, (IValidatable perhaps), but I wonder if I am making things needlessly complex.
I'm using VB6, so I can't use inheritance in my classes (VB6 supports classes but not inheritance). I can only define and implement interfaces. Because of this, and because of the way my current interfaces are designed, I'm duplicating a lot of boiler-plate code in my implementation classes. I am thinking of solving this with an inversion-of-control approach. For example, I was thinking of defining a single concrete QueryField class, which could be initialized with a collection of IValidationRule instances that define what validation rules to use, then the QueryField.Validate() method would just collect the results of executing each rule. This way, the validation rules can be tailored to each field, but the QueryField class can handle all the common field-related stuff (field name, field length, required/not required checks, etc.).
How Can I Improve This?
I'm interested in any refactoring suggestions and hints on improving the current design. Also, I'm not necessary tied down to domain-centric validation; other suggestions are welcome. The main motivation behind using domain-centric validation was to keep increase encapsulation, and allow query message and field objects to be used in a non-GUI environment, without having to rewrite all the validation logic.
When you initialize a QueryField object, pass a label to it from the GUI. Then it's the UI that is responsible for setting the label name which seems reasonable to me.
I don't think this is necessary.
What you are describing doesn't really sound like IoC but rather just plain old composition. Since you can't even use inheritance this improvement seems to make sense. Generally you want to prefer composition to inheritance anyways. However if you are almost done with the work then I wouldn't bother refactoring this late in the game.

Resources