code_junkie

Validation in a Domain Driven Design

Nov 14th, 2011
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. public interface IValidator<T>
  2. {
  3. bool IsValid(T entity);
  4. IEnumerable<string> BrokenRules(T entity);
  5. }
  6.  
  7. public class OrderPersistenceValidator : IValidator<Order>
  8. {
  9. public bool IsValid(Order entity)
  10. {
  11. return BrokenRules(entity).Count() > 0;
  12. }
  13.  
  14. public IEnumerable<string> BrokenRules(Order entity)
  15. {
  16. if (entity.Id < 0)
  17. yield return "Id cannot be less than 0.";
  18.  
  19. if (string.IsNullOrEmpty(entity.Customer))
  20. yield return "Must include a customer.";
  21.  
  22. yield break;
  23. }
  24. }
  25.  
  26. person.Address = "123 my street";
  27. person.City = "Houston";
  28. person.State = "TX";
  29. person.Zip = 12345;
  30.  
  31. person.ChangeAddress(.......);
  32.  
  33. bool IsVerifiedBy(TEntity candidate)
  34.  
  35. IEnumerable<string> BrokenRules(TEntity canditate)
  36.  
  37. bool IsVerifiedBy(TEntity candidate)
  38. {
  39. return BrokenRules(candidate).IsEmpty();
  40. }
  41.  
  42. IEnumerable<string> BrokenRules(TEntity candidate)
  43. {
  44. if (someComplexCondition)
  45. yield return "Message describing cleary what is wrong...";
  46. if (someOtherCondition)
  47. yield return
  48. string.Format("The amount should not be {0} when the state is {1}",
  49. amount, state);
  50. }
Add Comment
Please, Sign In to add comment