How to avoid duplicate validation logic between domain and application scopes?

Any object in my domain model has several invariants that must be respected - the project name must be at least 5 characters long, there must be a certain product that must be associated with the project, the deadline must not be before the current date and time, etc.

Obviously, I want the client to be able to display validation-related error messages, but I don't want to constantly maintain validation rules between several different levels of the program - for example, in widgets, controllers, application service or command object, and domain. Also, the seemingly descriptive error message is view related and does not belong to the domain layer. How can I resolve these dilemmas?

+3


source to share


2 answers


I would throw certain exceptions related to your expected error conditions. This is standard for exception handling in general and will help with your problem. For example:

public class ProjectNameNotLongEnoughException : System.Exception

or

public class DueDatePriorToCurrentDateException : System.Exception



Mark these possible exceptions in the xml comments for methods that might throw them so that applications written against your domain model will know to watch for these exceptions and can submit a message in the application presentation. It also allows you to localize error messages based on culture without cluttering your domain model with presentation issues.

If you choose to do client side validation, I'm afraid you won't be able to get your cake and eat it. In this case, you might have to duplicate the validation logic to achieve the desired functionality while maintaining your architecture.

Hope this helps!

+1


source


While a descriptive error message may seem more relevant to a view moreso than a business, a descriptive error message actually embodies the business rule contained in the domain model - and when throwing an exception of any kind, it is best to pass some descriptive message. This message can be re-rendered for layers to eventually display the user.



Now, when it comes to lookahead (for example, a widget that allows the user to enter only certain characters or select from a certain range of options), an object can contain some constants or methods that return a dynamically expressed regex that can be used by the view model and, in turn, implemented by widgets.

-1


source







All Articles