I've been researching using a service layer to validate my domain models before persisting them to a database.
I found the following example of using extension methods to validate my models, but was wondering if there were any specific disadvantages to doing so? I don't see validation (aside from Data Annotations) mentioned all that much.
I was thinking of implementing the following:
public class FooService : IFooService {
public bool Add(Foo foo) {
if (!foo.IsValid()) {
return false
}
try ... catch
}
}
public static class validationExtensions {
public static bool IsValid(this Foo foo) {
// Call my validation implementation here
}
}
I'm nervous to do this, as I don't see this recommended/implemented much. Thoughts?
Domain objects should be self validating, this is simple OOP. They should not be allowed to get into invalid state in the first place. Properly designed domain object enforces all internal invariants without relying on external code. Otherwise the encapsulation is broken and your objects are really just a dumb data containers with getters and setters.
The word 'validation' can also be a very dangerous overgeneralization, that tend to shift focus from domain and objects to dumb data containers tailored to a choice of UI framework. This is why DDD book never mentions the 'validation' issue at all. I find it more useful to think about invariant than about validation. Invariants can be as simple as 'social security number can not have letters', in which case a Value object should be used. Or more complex like 'order is considered to be delinquent if it was not payed within 2 weeks' which can be encapsulated within order.IsDelinquent()
or similar method. Note that in the first case we eliminate the possibility of object becoming invalid by implementing SocialSecurityNumber
class. And in the second case we use the word 'delinquent' from ubiquitous language instead of generic 'valid'. Please see similar answers: 1, 2, 3.
As a side note, you should probably take all 'DDD' advices from ASP.NET crowd with a grain of salt. ASP.NET MVC is a great framework but the learning material confuses Domain model with View model. Most of the examples consider 'domain' object to be the same as data container with getters and setters, without any encapsulation. DDD is technology agnostic, so you can always do a reality check by asking yourself 'would this make sense in a console app?' or 'would this make sense in a non-UI project?'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With