Skip to content

Instantly share code, notes, and snippets.

@vkhorikov
Last active October 16, 2019 23:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vkhorikov/5f0c7167250edb17cd2f to your computer and use it in GitHub Desktop.
Save vkhorikov/5f0c7167250edb17cd2f to your computer and use it in GitHub Desktop.
With primitive obsession
public class Customer
{
public string Name { get; private set; }
public string Email { get; private set; }
public Customer(string name, string email)
{
// Validate name
if (string.IsNullOrWhiteSpace(name) || name.Length > 50)
throw new ArgumentException("Name is invalid");
// Validate e-mail
if (string.IsNullOrWhiteSpace(email) || email.Length > 100)
throw new ArgumentException("E-mail is invalid");
if (!Regex.IsMatch(email, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
throw new ArgumentException("E-mail is invalid");
Name = name;
Email = email;
}
public void ChangeName(string name)
{
// Validate name
if (string.IsNullOrWhiteSpace(name) || name.Length > 50)
throw new ArgumentException("Name is invalid");
Name = name;
}
public void ChangeEmail(string email)
{
// Validate e-mail
if (string.IsNullOrWhiteSpace(email) || email.Length > 100)
throw new ArgumentException("E-mail is invalid");
if (!Regex.IsMatch(email, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"))
throw new ArgumentException("E-mail is invalid");
Email = email;
}
}
public class CustomerController : Controller
{
[HttpPost]
public ActionResult CreateCustomer(CustomerInfo customerInfo)
{
if (!ModelState.IsValid)
return View(customerInfo);
Customer customer = new Customer(customerInfo.Name, customerInfo.Email);
// Rest of the method
}
}
public class CustomerInfo
{
[Required(ErrorMessage = "Name is required")]
[StringLength(50, ErrorMessage = "Name is too long")]
public string Name { get; set; }
[Required(ErrorMessage = "E-mail is required")]
[RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$",
ErrorMessage = "Invalid e-mail address")]
[StringLength(100, ErrorMessage = "E-mail is too long")]
public string Email { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment