Value objects in DDD?

Value Objects is one of the component of DDD.

Identity is fundamental for entities. However, there are many objects and data items in a system that do not require an identity and identity tracking, such as value objects.

Let say Money value or DateTime or Value of other reference entiity as value object from aggregate root.

A value object can reference other entities. For example, in an application that generates a route that describes how to get from one point to another, that route would be a value object.

Important characteristics of value objects

There are two main characteristics for value objects:

  • They have no identity.
  • They are immutable.


Important to rememeber below the points

  • Never allow a Value Object to exist with an invalid value.
  • Never allow a Value Object to be mutated
  • Building the Value Object Should be built-in type exception string and class.
  • Never worried about the Input values.


How do we create string type into Value object?

Let us consider EmailAddress need to do validate emailId logic from string into value object.

  • It should be struct type (build in primitive type), should n't be string or class reference.
  • It should not be inherent / dervied from any class. that class should be seald.
  • It wrapped the value of string from the class with should value with constructor.
  • It should be handle exception / throw the error, when It would be invalid value
  • It should be validate string value checks equality using IEquatable<T> and also need to compare that value using IEqualityComparer<T>, IComparable


   public sealed class EmailAddress
    {
        private readonly string _emailAddressValidation = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
                + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
                + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
        private readonly string emailAddress;
        public EmailAddress(string emailAddress)
        {
            this.emailAddress = emailAddress;
        }

        public static EmailAddress CreateEmailAddress(string emailAddress)
        {
            if (!new EmailAddressAttribute().IsValid(emailAddress))
                throw new InvalidDataException(emailAddress);

            //OR

             if(!EmailIsValid(emailAddress))
                 throw new InvalidDataException(emailAddress);

            return new EmailAddress(emailAddress);
        }

        public string GetEmailAddress()
        {
            return emailAddress;
        }

        public override string ToString()
        {
            return GetEmailAddress();
        }        
 public class EmailAddressValidator : IEquatable<EmailAddress>, IEqualityComparer<EmailAddress>, IComparable        




Conclusion:

There is no identity and Immutable for this value object, might have value to reference of another entity.

要查看或添加评论,请登录

jayamoorthi parasuraman的更多文章

社区洞察

其他会员也浏览了