Skip to content

Instantly share code, notes, and snippets.

@jltrem
Created February 22, 2024 15:28
Show Gist options
  • Save jltrem/b9e9afc874034e70d44f2a7d32abdf03 to your computer and use it in GitHub Desktop.
Save jltrem/b9e9afc874034e70d44f2a7d32abdf03 to your computer and use it in GitHub Desktop.
Immutable Domain Types example
public record Contact
{
public required PersonalName Name { get; init; }
public required EmailAddress Email { get; init; }
}
public record PersonalName
{
public required string First
{
get => _first;
init => _first = ValidateName(value, nameof(First));
}
public required string Last
{
get => _last;
init => _last = ValidateName(value, nameof(Last));
}
private readonly string _first = "";
private readonly string _last = "";
private static string ValidateName(string name, string argument = "")
{
string value = name?.Trim() ?? "";
bool ok = value.Length > 1 && value.Length < 80;
if (!ok) throw new ArgumentOutOfRangeException(argument);
return value;
}
}
public record EmailAddress
{
public string Value => _value;
public EmailAddress(string value)
{
_value = value?.Trim() ?? "";
if (!_regex.IsMatch(_value)) throw new ArgumentException("invalid email format");
}
private readonly string _value = "";
private static readonly Regex _regex =
new(@"^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment