Make Your Types Report Their State: C#: Enforce Object Validity: Listing 1
This more verbose Person object includes validation logic that ensures your object is always valid. Every transformation is checked both before and after any state changes. It adds some weight to the class, but that's all for ensuring correctness.
public class Person
{
private bool firstNameInitialized;
private string firstName;
public string FirstName
{
get
{
Debug.Assert(this);
return firstName;
}
set
{
Debug.Assert(this);
if (!string.IsNullOrEmpty(value)) firstName = value;
firstNameInitialized = true;
Debug.Assert(this);
}
}
private bool lastNameInitialized;
private string lastName;
public string LastName
{
get
{
Debug.Assert(this);
return lastName;
}
set
{
Debug.Assert(this);
if (!string.IsNullOrEmpty(value)) lastName = value;
lastNameInitialized = true;
Debug.Assert(this);
}
}
public static implicit operator bool(Person p)
{
bool isValid = true;
if (p.firstNameInitialized == true)
isValid &= !string.IsNullOrEmpty(p.FirstName);
if (p.lastNameInitialized == true)
isValid &= !string.IsNullOrEmpty(p.LastName);
return isValid;
}
}