Skip to content

Instantly share code, notes, and snippets.

@ArisAgnew
Last active June 20, 2021 19:55
Show Gist options
  • Save ArisAgnew/28bfc71fa7759a083528c2ff56473ade to your computer and use it in GitHub Desktop.
Save ArisAgnew/28bfc71fa7759a083528c2ff56473ade to your computer and use it in GitHub Desktop.
Refactoring If-Else to Value Object
//If-Else Approach
public class User
{
public string Name { get; set; }
public string Email { get; set; }
public void ChangeEmail(string email)
{
if (!IsEmailValid(email))
throw new ArgumentException("{email} is not valid.", email);
Email = email;
}
private bool IsEmailValid(string email)
{
try
{
var mail = new MailAddress(email);
return true;
}
catch (FormatException)
{
return false;
}
}
}
//Value Object Approach
public class UserEmail
{
public string Email { get; private set; }
public UserEmail(string email)
{
if (!IsEmailValid(email))
throw new ArgumentException("{email} is not valid.", email);
Email = email;
}
private bool IsEmailValid(string email)
{
try
{
var mail = new MailAddress(email);
return true;
}
catch (FormatException)
{
return false;
}
}
/* Equals and GetHashCode should be overridden to ensure structural equality. */
}
public class User
{
public string Name { get; set; }
public UserEmail UserEmail { get; private set; }
public void ChangeEmail(UserEmail userEmail)
{
UserEmail = userEmail;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment