views:

391

answers:

1

When you a set a property's value, you can either validate before or after updating the internal value.

If validating before, you could throw an exception if the new value is invalid. The object is then always in a valid state.

If validating after, undo is desired (i.e. via IEditableObject), so the user can cancel the edit any time. We also have the option of either throwing an exception here or expose errors via IDataErrorInfo.

I don't think IDataErrorInfo makes sense if validating before the set. Some also may argue throwing an Exception is not warranted in validation scenarios.

Validating after works great in scenarios where the custom object is contained in BindingList and set as datasource to a grid.

Validating before works ok with grids too but you kind of have to throw an exception in order to signal the setting of the property value failed to the data grid (without a lot of extra code)

I am also not comfortable with my domain objects implementing IEditableObject and IDataErrorInfo, INotifyPropertyChanged, etc. It leaves the domain object cluttered with extra concerns. But it seems unavoidable if you want to place nice with databinding. I could create a wrapper, DTO perhaps, but I'm not too crazy about having to write mostly dummy extra code just to support these databinding bits.

How do you validate objects (preferrably in the context of databinding and UI)?

+1  A: 

See my answer to Business Objects, Validation And Exceptions : I think Paul Stovell's ideas about validation (summed up in this article) are incredibly powerful.

By implementing IDataErrorInfo in your domain entities (and possibly IEditableObject and INotifyPropertyChanged), you give them the ability to get databound on many .NET presentation technologies (Windows Forms, WPF, ASP .NET...) without much code. Or you could use them in scripts or batches (ie non UI processes) and still have the possibility to validate them against business rules : either smoothly (query the current entity state) or the hard way (throw an exception on saving if invalid).

The main thing is that with this pattern, your domain entities are responsible for their own validation (which is good, and certainly does not appear to me like extra concerns). They enforce it by throwing meaningful exceptions on saving if they are in an invalid state. And they can play nicely with your code (UI or not), by letting you know if they are valid or not if you care to ask first.

I even apply these principles beyond the domain model in my software factory project (still in early stages) : Salamanca.

Mac
I had found Paul Stovell's blog before writing up this q and that's where I found myself in a dilemma whether to go with his approach or not. Indeed, I ended up using his approach. My implmentation of it is a bit more complex which I don't like, but unavoidable. I'm still not fully convinced this is the way to go but haven't found an alternative that's better.
Jiho Han