Home > design patterns > Where we should put validation for domain model

Where we should put validation for domain model

November 15Hits:1
Advertisement

I still looking best practice for domain model validation. Is that good to put the validation in constructor of domain model ? my domain model validation example as follows:

public class Order  {     private readonly List<OrderLine> _lineItems;      public virtual Customer Customer { get; private set; }     public virtual DateTime OrderDate { get; private set; }     public virtual decimal OrderTotal { get; private set; }      public Order (Customer customer)     {         if (customer == null)             throw new  ArgumentException("Customer name must be defined");          Customer = customer;         OrderDate = DateTime.Now;         _lineItems = new List<LineItem>();     }      public void AddOderLine //....     public IEnumerable<OrderLine> AddOderLine { get {return _lineItems;} } }   public class OrderLine {     public virtual Order Order { get; set; }     public virtual Product Product { get; set; }     public virtual int Quantity { get; set; }     public virtual decimal UnitPrice { get; set; }      public OrderLine(Order order, int quantity, Product product)     {         if (order == null)             throw new  ArgumentException("Order name must be defined");         if (quantity <= 0)             throw new  ArgumentException("Quantity must be greater than zero");         if (product == null)             throw new  ArgumentException("Product name must be defined");          Order = order;         Quantity = quantity;         Product = product;     } } 

Thanks for all of your suggestion.

Answers

There's an interesting article by Martin Fowler on that subject that highlights an aspect most people (including me) tend to overlook:

But one thing that I think constantly trips people up is when they think object validity on a context independent way such as an isValid method implies.

I think it's much more useful to think of validation as something that's bound to a context - typically an action that you want to do. Is this order valid to be filled, is this customer valid to check in to the hotel. So rather than have methods like isValid have methods like isValidForCheckIn.

From this follows that the constructor should not do validation, except perhaps some very basic sanity checking shared by all contexts.

Again from the article:

In About Face Alan Cooper advocated that we shouldn't let our ideas of valid states prevent a user from entering (and saving) incomplete information. I was reminded by this a few days ago when reading a draft of a book that Jimmy Nilsson is working on. He stated a principle that you should always be able to save an object, even if it has errors in it. While I'm not convinced that this should be an absolute rule, I do think people tend to prevent saving more than they ought. Thinking about the context for validation may help prevent that.

As I'm sure you already know...

In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created. It is called a constructor because it constructs the values of data members of the class.

Checking validity of the data passed in as c'tor parameters is definitely valid in the constructor - otherwise you're possibly allowing the construction of an invalid object.

However (and this is just my opinion, can't find any good docs on it at this point) - if data validation requires complex operations (such as async operations - perhaps server-based validation if developing a desktop app), then it's better put in an initialization or explicit validation function of some sort and the members set to default values (such as null) in the c'tor.



Also, just as a side note as you included it in your code sample...

Unless you're doing further validation (or other functionality) in AddOrderLine, I'd most likely expose the List<LineItem> as a property rather than have Order act as a facade.

Despite the fact this question is a little stale, I'd like to add something worthwhile:

I'd like to agree with @MichaelBorgwardt and extend by bringing up testability. In "Working Effectively with Legacy Code", Michael Feathers talks a lot about obstacles to testing and one of those obstacles is "difficult to construct" objects. Constructing an invalid object should be possible, and as Fowler suggests, context dependent validity checks should be able to identify those conditions. If you can't figure out how to construct an object in a test harness you're going to have trouble testing your class.

Regarding validity I like to think of control systems. Control systems work by constantly analyzing the state of an output and applying corrective action as the output deviates from the set point, this is called closed loop control. Closed loop control intrinsically expects deviations and acts to correct them and that's how the real world works, which is why all real control systems typically use closed loop controllers.

I think using context dependent validation and easy to construct objects will make your system easier to work with down the road.

Related Articles

  • Where we should put validation for domain modelNovember 15

    I still looking best practice for domain model validation. Is that good to put the validation in constructor of domain model ? my domain model validation example as follows: public class Order { private readonly List<OrderLine> _lineItems; public vi

  • Automagic (or not quite so) Domain Model Class ValidationOctober 6

    The Task I was assigned a small task, concerning validation of Domain-Model classes. The Validation for a String property of one of our Models was required to be unique across the whole Table. And as this already was halfway implemented after 20 minu

  • Validation and data persistence in a domain modelSeptember 27

    My (first and current) workplace (a .NET shop) suffers from an over-abundance of anemic domain models, to the extent that I don't really know how validation and data persistence should be handled in a proper domain model. Data Persistence One option

  • How to present domain model exceptions thrown through validationMay 14

    In domain model of my web application I've an entity Foo which can be created only by a pojo FooBean: Foo.newInstance(FooBean fooBean) (Might have been better a Builder-pattern.) In the factory methode newInstance() the pojo FooBean is validated and

  • Where to put format validation in a CQRS "stylish" domain model?June 19

    It feels right to put format validation inside the domain objects (VOs or entities) because it is the natural place for high cohesion and the domain knows best what every domain description/attribute/property means. Many DDD practitioners and books a

  • Domain Model, validation, and pushing errors to the modelOctober 8

    Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags. That said how do you handle pieces of validation that require a trip to the database? For example, you have an domain objec

  • Handling validation discrepancies between user mental model and domain modelFebruary 6

    I am implementing an image editing feature in a mobile productivity app. The feature is used to crop and rectify a camera image of a document. (This is also known as dewarping, straightening, or perspective correction.) In particular, I am implementi

  • Does "Inversion of Control" promote "Anemic Domain Model"?May 1

    When I used IoC Container in my last project, I ended up with anemic entities and most of my business logic in Stateless Services. I have seen projects written by other developers that utilize "Inversion of Control" and they are always "Ane

  • Building a Domain Model - An Introduction to Persistence AgnosticismFebruary 24

    With so much water flowing under the Domain Models bridge over the last few years, it's rather hard to dig deep into the key concepts without rippling even more confusion in the already agitated creek. Moreover, with tons of MVC implementations proli

  • Building a Domain Model – Integrating Data MappersMarch 16

    While there's still a huge number of cases where Domain Models are considered an overkill "enterprisey" solution that doesn't jive with the natural pragmatism that proliferates throughout the world of PHP, they're steadily breaching the minds of

  • Recovering an anemic domain model into a multitier architectureOctober 11

    I have spent the past several days learning about domain driven design and attempting to apply it to a current project. I decomposed the problem domain into the canonical logical components: domain, infrastrucutre, and presentation. Having completed

  • The Null Object Pattern - Polymorphism in Domain ModelsOctober 17

    While certainly a far cry from being canonical, it can be said that Orthogonality is the quintessence of software systems that rest on the foundations of "good design", where the constituent modules are neatly decoupled from one another, making

  • What is the business cost of anemic domain modelJanuary 17

    I am looking to quantify the cost or problems of bad software development practices. Specifically can software that has been developed resulting in an anemic domain model be quantifiable in terms of business cost or risk? My initial thoughts (which a

  • Anemic Domain Model vs. DDD by definition example(s)?May 28

    What is an example of "Business Logic" that should reside in the DomainModel i.e. inside an Entity instead of inside a (Domain) Service, as well as some example logic that should be in a service. Here are what I would consider to be pretty clear

  • Do MVC web frameworks favor anemic domain model in order to avoid duplication?August 12

    Binding directly the form to your model helps a lot to get rid of boiler plate code, but that means that your model must have a getter/setter for each property otherwise it wouldn't be possible. Another choice would be to create another layer (DTO) o

  • Where to validate domain model rules that depend on database content?September 7

    I'm working on a system that allows Administrators to define Forms that contain Fields. The defined Forms are then used to enter data to the system. Sometimes the Forms are filled by a human via a GUI, sometimes the Form is filled based on values rep

  • Practices for domain models in Javascript (with frameworks)September 15

    This is a question I've to-and-fro'd with for a while, and searched for and found nothing on: what're the accepted practices surrounding duplicating domain models in Javascript for a web application, when using a framework like Backbone or Knockout?

  • Rich Domain Models - how, exactly, does behavior fit in?

    Rich Domain Models - how, exactly, does behavior fit in?October 6

    In the debate of Rich vs. Anemic domain models, the internet is full of philosophical advice but short on authoritative examples. The objective of this question is to find definitive guidelines and concrete examples of proper Domain-Driven Design mod

  • Do RESTful APIs tend to encourage anemic domain models?January 14

    I'm working on a project in which we are trying to apply both domain-driven design and REST to a service-oriented architecture. We aren't worrying about 100% REST compliance; it would probably be better to say we are trying to build resource-oriented

  • Anemic domain models - what sort of methods a domain object might need?January 21

    This question might seem strange, but it's something I've faced sometimes. I've been trying to adopt DDD, however I'm always facing the problem of anemic domain models. The problem is that when I start to think about what should be the behaviors of t

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 0.432 s.