I'm writing a VB.NET Winforms project based on MVVM (using Winforms binding). My instinct is to never allow a domain entity be in an invalid state. This requires that I do validation checks in the constructor for new entities and in each setter for existing entities:
Public Class Product
Public Sub New(ProductID as Integer, Name as String)
If ProductID > 0 AndAlso Name.Length > 5 Then
_ProductID = ProductID
_Name = Name
Else
Throw New InvalidProductException
End If
End Sub
Private _ProductID as Integer
Public Property ProductID as Integer
Set(value as String)
If value > 0 then
_ProductID = value
Else
Throw New InvalidProductException
End If
End Set
End Property
'Same principle as above for Name setter.
End Class
Then I ran across Data Annotations, which seemed pretty slick. I noticed that most people using Data Annotations allow the domain entity to become invalid temporarily, and then validate the entity at some later point with a call to Validate.ValidateObject. By this point the entity is invalid and the original state has been lost unless you have some other mechanism to roll it back.
Two Questions:
1) Do you allow domain entities to become temporarily invalid?
2) Based on your answer to #1, what techniques do you use to validate the entity?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…