user676767
user676767

Reputation: 255

Nested Validation

I'm wondering what the best approach is to take with validation.

If I have a complex object object composed of primitives, associations, and collections of other custom objects, should an IsValid() method validate the child objects as well as the required fields/keys of the root object?

If yes, should this be in some sort of abstract class, or is it best to use interfaces? With abstract, I would need to cast my child object interfaces to their concrete class definition in order to use an abstract method, whereas with interface validation I believe I can keep my children as interfaces as I call their validation methods.

Also, I'm not using MVC, but MVP with web forms (and trying to employ DDD principles).

Thanks.

UPDATE

I have a Aggregate root of ScheduledMeeting:

class ScheduledMeeting : BaseValidation
{
     ScheduledMeetingID {get;set;}
     ITimeSlot TimeSlot {get;set;}
     IList<IMeetingAssignee> Assignees{get;set;}
     DateTime meetingDate {get;set;}

     AssignEmployees(IList<IEmployees> employees){}
}

Currently, there exists an abstract class of BaseValidation, which looks similar to the following:

 public bool isValid(bool validateKeys)
    {
        if (validateKeys)
        {
            ValidateRequiredFields();
            ValidateKeys();
        }
        else
        {
            ValidateRequiredFields();
        }
        return true;
    }  

where ValidateRequiredFields() and ValidateKeys() are overridden in implementing objects.

If I'm to use the above and cascade to IMeetingAssigned, I would need to loop in both ValidateKeys() and ValidateRequiredKeys() in ScheduledMeeting, casting IMeetingAssigned to concrete MeetingAssigned before then calling either ValidateKeys() or ValidateRequiredKeys() in this object (as it would also implement BaseValidation), and so on, all the way down.

UPDATE 2

I am stuck with .NET 3.5, and so cannot implement Code Contracts, etc. (as far as I'm aware).

Upvotes: 0

Views: 635

Answers (2)

Dennis Traub
Dennis Traub

Reputation: 51644

Since you're employing Domain Driven Design I assume you have identified and modelled your classes as Aggregates.

To answer your question: Yes, the Aggregate Root is responsible of making sure that itself and everything that's contained is valid at any given point in time. The Aggregate Root should never be in an invalid state.

Update from the comments: Get rid of your validation interface. An Aggregate should never be in an invalid state in the first place. Whenever the state of your AR is about to change, make sure the resulting state wouldn't brake any invariants. If it would, the AR should reject the modification.

Enforce the invariants, don't validate after the fact.

Upvotes: 0

Martijn van den Broek
Martijn van den Broek

Reputation: 1381

Don't let your objects get into an invalid state in the first place, saves you a lot of 'IsValid' trouble.

Upvotes: 2

Related Questions