For reference:
A Value Object is an immutable type that is distinguishable only by the state of its properties. That is, unlike an Entity, which has a unique identifier and remains distinct even if its properties are otherwise identical, two Value Objects with the exact same properties can be considered equal.
Please see the code below:
public class PersonFirstName
{
//public string FirstName { get; set; }
private string _firstName;
public PersonFirstName(string firstName)
{
if (firstName == null)
throw new ArgumentNullException("Surname");
if (!PersonFirstName.IsValid(firstName))
throw new ArgumentException("Invalid value.", "Surname");
this._firstName = firstName;
FirstName = firstName;
}
public PersonFirstName() //for NHibernate
{
}
public static bool IsValid(string candidate)
{
if (string.IsNullOrWhiteSpace(candidate))
return false;
if (candidate.Length > 255)
return false;
return true;
}
public string FirstName
{
get { return _firstName; }
private set
{
_firstName = value;
}
}
public override bool Equals(object obj)
{
PersonFirstName PersonFirstName = obj as PersonFirstName;
if (ReferenceEquals(PersonFirstName, null))
return false;
return _firstName == PersonFirstName.FirstName;
}
public override int GetHashCode()
{
return _firstName.GetHashCode();
}
}
and the Unit Test below:
[Test]
public void Domain_FirstNameValue_ValueObjectCreated()
{
//Arrange
var PersonFirstName1 = new PersonFirstName("Ian");
var PersonFirstName2 = new PersonFirstName("Ian");
//Act
var firstNameCompareResult = PersonFirstName1.Equals(PersonFirstName2);
//Assert
Assert.True(firstNameCompareResult);
}
I would be grateful for comments on the quality of this test.