I asked this question yesterday: https://softwareengineering.stackexchange.com/questions/364895/entity-and-value-object-are-not-part-of-the-ubiqtious-language-should-this-stop. I originally decided to introduce a ValueObject class as described here: https://lostechies.com/jimmybogard/2007/06/25/generic-value-object-equality/, which contained equality methods for all value objects i.e. all Value Objects inherited from ValueObject the value object class. However, this approach was criticised.
Please see the code below:
public sealed class Surname : IEquatable<Surname> { private readonly string _value; public Surname(string surname) { if (surname.Length==0) throw new ArgumentException("Invalid value.", "Surname"); this._value = surname; } public string Value { get { return _value; } } public static bool operator ==(Surname surname1, Surname surname2) { if (!ReferenceEquals(surname1, null) && ReferenceEquals(surname2, null)) { return false; } if (ReferenceEquals(surname1, null) && !ReferenceEquals(surname2, null)) { return false; } return surname1.Equals(surname2); } public static bool operator !=(Surname surname1, Surname surname2) { return !(surname1== surname2); } public bool Equals(Surname other) { if (other != null) { return _value == other._value; } return base.Equals(other); } public override bool Equals(object obj) { return Equals(obj as Surname); } public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + _value.GetHashCode(); return hash; } } }
It is a DDD Value Object for a Surname.
I have added some methods for equality and:
Q1) I would like some feedback on the quality of them.
Q2) This question (point one) links to a presentation by Eric Evans where he appears to advise against introducing equality for Entities. Is it advisable to always compare entities by reference these days?