DDD Question: Where does required info validation belong for an Entity?

Let’s say I have a small hierarchy of object: Faults and Parts. A Fault can contain many parts, and a part has no meaning without being associated to a Fault. To ensure that I have no Parts without a parent Fault, I have this basic code in place:

public class Part
{
    private Part()
    {
    }
 
    public string Description { get; set; }
 
}
 
public class Fault
{
    private IList<Part> _parts = new List<Part>();
 
    public IList<Part> Parts { get { return _parts; } }
    
    public Part CreatePart()
    {
        Part part = new Part;
        _parts.Add(part);
        return part;
    }
}

This ensures that I never have a Part in an “invalid” state – without an owning parent.

I also have a business rule that say that I’m not allowed to have a Part without a description. My typical implementation of this business rule has been in the UI layer – my Presenter would have the logic to require a user to enter a description when creating adding a part to a fault.

public class PartCreationPresenter
{
 
    Part _part;
 
    public PartCreationPresenter(Part part)
    {
        _part = part;
    }
 
    public DescriptionProvided(string desc)
    {
        if (string.IsNullOrEmpty(desc))
        {
            view.ShowDescriptionRequiredMessage();
        }
        else
        {
            _part.Description = desc;
        }
    }
 
}

Here’s the question:

Should this “require a description” logic be in the UI layer (Presenter) the way I have it, or should I put it in the Part object and have an IsValid flag of some sort on that object?

I don’t like having this coded in the presenter only. It makes the business rule very easy to break – create a part from anywhere else, and you can ignore this rule. But I’m not sure I like it in the Part object, because it would make the presenter difficult to code. How would I execute the specific view.ShowDescriptionRequiredMessage() method if the rule is coded in the Part?

Any opinions, suggestions, articles, etc. are very welcome. I’m very interested in hearing how other people are handling this situation.


Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Derick Bailey

Derick Bailey is an entrepreneur, problem solver (and creator? :P ), software developer, screecaster, writer, blogger, speaker and technology leader in central Texas (north of Austin). He runs SignalLeaf.com - the amazingly awesome podcast audio hosting service that everyone should be using, and WatchMeCode.net where he throws down the JavaScript gauntlets to get you up to speed. He has been a professional software developer since the late 90's, and has been writing code since the late 80's. Find me on twitter: @derickbailey, @mutedsolutions, @backbonejsclass Find me on the web: SignalLeaf, WatchMeCode, Kendo UI blog, MarionetteJS, My Github profile, On Google+.
This entry was posted in .NET, Analysis and Design, Design Patterns, Domain Driven Design, Model-View-Presenter. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Matt G

    Seems like Part should be a value object whose constructor accepts a description, rather than using a setter. Constructor logic would then guarantee that the Part is valid.

    I don’t have a good answer on validation except to say that I think you should make sure your domain is valid regardless of UI. If your presenter is influencing your domain model, I’d question whether the model is domain driven in the first place. To that end, wouldn’t a little code duplication would be okay?

    I’m no expert on DDD, though, so I may be off base. Just my thoughts having grappled with the same question. I’m interested to hear others weigh in.

  • http://www.lostechies.com/blogs/derickbailey derick.bailey

    @Matt G

    Ah – yeah, I hadn’t thought about requiring the description to be provided when I call Fault.CreatePart…

    Fault.CreatePart(“my description”)

    This does bring up the question, though, of whether or not the description of a part is really a domain rule, or an application rule. Does my domain really truly require the part description, or is that merely a function of the application?

    … more stuff to ponder.

    thanks for input, Matt!

  • http://scottic.us Scott Bellware

    The invariant logic for an object should be in (or with) that object, regardless of the clients that use that object.

    With the validation logic in the presenter, the logic is placed with the observer rather than the observed, which functionally works, but is structurally suspect.

    The client code (the presenter) can use the object and its invariant logic to determine what course the client should take, but the validation logic itself can remain in or close to the abstraction where it is more natural and native.

  • http://jimmybogard.lostechies.com Jimmy Bogard

    Or: don’t make a setter at all. Don’t allow a domain object to be in an “invalid” state.

    Invalid means different things in different contexts. Some things during creation are different than during fulfillment. Try task-specific methods on the domain object that do their own validation. If you can’t do it, it won’t.

  • http://www.tobinharris.com Tobin Harris

    As the others said, it makes more sense to keep that logic firmly in the domain model.

    I quite like the pattern where I allow domain objects to get into invalid state, but they usually can’t be *persisted* if they’re valid.

    You’ve probably seen this loads of times, but as an example you’d have this on your Fault class.

    public ValidationError[] Validate()
    {
    IList errors = new List();
    if(_parts.Count == 0 )
    errors.Add(new ValidationError(“Fault must have at least one part”));

    if(_parts.Any(p=>string.IsNullOrEmpty(p.Description))
    errors.Add(new ValidationError(“All parts must have a description”));

    return errors;
    }

    ValidationErrors can be richer too. For example, they can contain info to help other layers work with the error info. Perhaps containing error codes that are then converted to locale-specific error messages in the UI. Or they could contain MemberInfo instances pointing to Fault/Part members, thus allow highlighting of UI fields.

    Rails uses a similar approach, as does NHibernate Validations AFAIK.

  • http://colinjack.blogspot.com Colin Jack

    Encapsulating collection seems sensible but your entities and aggregate roots can get filled with silly little detail related methods like CreatePart. If your aggregate has a few collections and each collection has behavior (which they often do) then the aggregate root gets very noisy very quickly so instead I’d have a custom PartsCollection and use the custom collection mapping approach:

    http://colinjack.blogspot.com/2008/09/nhibernate-mapping-custom-collections.html

    Onto Part, depends what/when it needs it and in what context. Depending on the situation IsValid()/CanX() might be appropriate, but in this case I’d just have a constructor that takes the description.

    @bogardj
    “Or: don’t make a setter at all. Don’t allow a domain object to be in an “invalid” state.”

    Do you actually do this and if so how, are you using Gregs messaging approach (or a variant of)? I’m guessing that your aggregates all only accept messages, and at the end of each message the object is valid again…

    @Tobin
    Thats a pattern I’ve used a lot too.

  • http://www.lostechies.com/blogs/derickbailey derick.bailey

    thanks for all of the suggestions, everyone.

    it seems that the basic boilerplate response is that i need to put moving my validation logic into (or near) the entities in the domain model. I do agree with this – was just having a hard time getting my presenter to work with it.

    the ideas of having a collection of validation error messages / objects seems to be common among the solutions as well (for those in the comments, and for the emails i’ve recieved directly).

    i’m not fond of a lot of if-then statement littering my code, and handling specific broken rules like this is especially prone to massive if then statements, in my experience. perhaps some sort of strategy pattern for the rules, or command pattern, to execute when a rule is broken or satisfied, allowing me to register a specific command to execute in my specific contexts. i.e. my presenter could register a command to execute when the part’s description validation fails like this (not addressing the issue of creating a part in an invalid state, yet… and just a real rough idea of an API to call, definitely needs refining):

    public class PartPresenter
    {

    public PartPresenter(IPartView view, Part part)
    {
    part.ValidationRules.RegisterCommand(
    () => view.ShowDescriptionRequiredMessage(),
    PartValidationRules.Description,
    RuleState.Broken
    );

    part.ValidationRules.RegisterCommand(
    () => view.HideDescriptionRequiredMessage(),
    PartValidationRules.Description,
    RuleState.Satisfied
    );
    }

    }

    the first parameter of RegisterCommand is the command code i want to execute. the second parameter is the specific rule (possibly a delegate to the rule or some other way of identifying the rules that are available to the Part object). the third parameter is when to fire the command for this rule – when the rule is broken, or when the rule passes (is satisfied). this is just a rough API idea, and needs some refining. I think it’s one possible implementation of what everyone is saying, though.

    additional thoughts? suggestions for a better API here?

  • http://www.lostechies.com/blogs/joe_ocampo/ Joe Ocampo
  • nightshade427

    Joe Ocampo:
    That is a cool post. I am doing something very similar to the extension method approach. It seems to work very well especially in my case where I have several different ways I need to validate the entities based on the context they are used.

  • http://colinjack.blogspot.com Colin Jack

    > i’m not fond of a lot of if-then statement littering my
    > code, and handling specific broken rules like this is
    > especially prone to massive if then statements, in my
    > experience. perhaps some sort of strategy pattern for the
    > rules, or command pattern, to execute when a rule is
    > broken or satisfied, allowing me to register a specific
    > command to execute in my specific contexts

    One approach I’ve used is to model the conditions as little rules implementing something like IDomainRule and inheriting from ISpecification. You can thus say “new CustomerNameRule().IsSatisfiedBy(customer)”.

    The IDomainRule interface adds extra meta-data about the rule (not necessarily a description which would be resourced but maybe some other useful informaiton.

  • Neeva

    Great post and good discussion. One element, tied to webapps, that I see frequently missing is the notion of client side validation. The average ASP.NET developer uses ASP.NET validators to validate on both server and client side. While this is nice, it seperates the validation from the domain classes. I have yet to see a good solution to combine both worlds. Any ideas here?

  • http://colinjack.blogspot.com Colin Jack

    @Neeva
    I’d say either don’t combine both worlds, just repeat the validation in the domain (which will ofcourse do additional validation) or maybe generate your client side validation (e.g. JS) from your domain rules. There are other options of course…

  • http://tobin@tobinharris.com Tobin Harris

    @Neeva. I think that Ruby on Rails handles this quite nicely. It’s something like this (psudocode).

    void OnSave(){
    if( ! customer.Validate() )
    view.ShowErrors( customer.ValidationErrors );
    else
    customerRepos.Save( customer );
    }

    That would list the error messages at the top of the page after a user tries to submit.

    This is possible in ASP.NET too (MVC or otherwise).

    In Rails, because the validation errors also contain information about the object properties that were invalid, you can easily write code to highlight the appropriate text fields etc. Last time I did a Rails project, I added 5 lines of framework code on got this facility on every form in the project! You have to use a convention in your field naming for this, but that’s no bad thing IMHO.

  • shovavnik

    The way I see it, validation is layer-specific and required in one form or another on most every layer. This does two things: it provides an in depth validation (and data integrity) solution, and it forces communication between developers working on disparate parts of an application.

    The difficulty is usually figuring out what the minimal amount of validation is at any layer.

    For example, you could have a database record for an Employee that has a non-null BirthDate field. The “non-null” and “date” type are a form of validation that determine that every Employee record must assign a date type value to the BirthDate field.

    In the data access layer, the validation would probably just ensure that the value for the Employee class object’s BirthDate property can map correctly to the appropriate database field for the specific database provider.

    In the domain, you’d validate the actual value, based on domain/business rules. For example, an employee cannot be under 18 or over 65, or whatever. Whether the validation occurs only when persisting the data (which allows invalid state otherwise) or always depends on the application-specific requirements.

    On the client, you’re usually validating data entry, so the client is responsible for ensuring, for example, that the value is actually a date, possibly converting to the format to the format required by the domain classes (e.g., from 17/6/80 to 6/17/80 in some locales). In applications that allow invalid domain state, the client usually hooks into the domain validation in addition to the client-specific validation. So the client could optimize the process by also checking that the age is within domain-specified bounds by setting max and min values on a client validator control.

    When I describe a layered approach to validation with examples like this, I usually get a better response, because instead of thinking about WHERE to put the validation, the developers think about WHAT kind of validation is appropriate or requisite at any given level. The idea is to promote loose coupling and a non-layered validation approach defeats that purpose.

  • Sam

    The MS Enterprise Library Validation Block does a great job at solving this problem.

    Rather than using a set of if/else if/else blocks, properties on the domain object are decorated with a set of attributes which specify the conditions under which they are valid.

    My team has been using it in production code for the last couple of project, and it’s working very well.

    Example code here: http://msdn.microsoft.com/en-us/library/cc511873.aspx

  • http://colinjack.blogspot.com Colin Jack

    @Sam
    Attributes are too inflexible to use for all domain validation, they solve simple problems well but fall over badly in other situations:

    http://colinjack.blogspot.com/2008/03/domain-model-validation.html

    That’s my view on it anyway.

  • http://www.lostechies.com/blogs/derickbailey derick.bailey

    @Sam @Colin

    I agree with Colin. I’ve run into serious limitations using attributes for various purposes, in the past, and I tend to avoid them when I can, these days.

    On top of that, there are so many frameworks out there that want attributes to be used, it turns into a bunch of visual noise and really takes away from the simplicity of an object, after more than a few attributes are applied.

  • http://chadmyers.lostechies.com Chad Myers

    We’ve been successful using attributes and putting validation external. We’re not real strict on the “object can never be in an invalid state” thing. For testing, it’s easier to allow it to be invalid and we can use an ObjectMother or some common factory to assemble one for us when we need it in a valid state. The entity has all the information on-or-in itself to tell us whether it’s valid or not.

    public class Part
    {
    [Required]
    public string Description{ get; set; }
    }

    The “Required” attribute is also used to determine whether the column is nullable in the DB when we generate our DB from the domain. We also have other attributes like MaxStringLength, MustBePositive, and the like.

    For tricky situations, we can implement IValidated and do a custom IsValid() method, but we try to keep this to a minimum and limit the number of conditionals in these methods.

  • http://johnwest.spaces.live.com John

    I don’t believe in putting supporting methods in the object itself. What if the validation depends on another type of object? Or another method that needs to be called? Then, all of a sudden, your object becomes depending on other objects.

    I always create a ValidateX method in my business layer that returns a collection of strings. If the collection count is 0, there are no validation errors. Otherwise, there are, and I can display them. I call it in the presentation layer, and I also call it in my save method, and throw an execption if there are errors. This way, even if the developer forgets to check before trying to save, I’ll still prevent the save from occurring.

    So, I have the following:

    Part
    {
    prop1
    prop2
    prop3
    }

    PartsService, PartsBusinessLayer, whatever your name for Parts business layer code
    {
    public List Validate(Part p)
    {
    return strings containing errors, if any, otherwise empty collection
    This method might also call other business layer services, such as loading the fault to see if if supports this fault, or doing a calculation
    on the part cost to see if it’s too excessive, or whatever. I wouldn’t want these dependencies in my Part object.
    }

    public Part Save(Part p)
    {
    if (Validate(p).Count > 0)
    {
    throw exception, since user should have called Validate first to display the errors in a friendly fashion.
    }
    else
    {
    Save part
    }
    }
    }

    John