Validating domain model using extension methods

前端 未结 1 1243
自闭症患者
自闭症患者 2021-01-19 12:59

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 met

1条回答
  •  执笔经年
    2021-01-19 13:24

    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?'.

    0 讨论(0)
提交回复
热议问题