Last active
June 20, 2021 19:55
-
-
Save ArisAgnew/28bfc71fa7759a083528c2ff56473ade to your computer and use it in GitHub Desktop.
Refactoring If-Else to Value Object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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