Consider an example where the user enters values for customer object using a form in two aspx pages. With the first approach both the aspx pages need to validate that ID is greater than 0 and FirstName is not empty before calling the constructor. With the second option, both the pages can call the Validate function and show the error messages to the users.
Based on the above example I prefer the second option. However, when I'm researching the on the web, I keep seeing that it is more object oriented to throw exceptions right away and not let the object accept invalid data. As I said earlier with exceptions, every page calling this constructor needs to validate the inputs are valid. I don't like repeating the logic so I prefer the second option.
What is the preferred option in terms of Domain Driven Design?
Option 1
public class Customer{
public int ID { get; set; }
public string FirstName { get; set; }
public Customer(int ID, string FirstName){
if (ID < 0)
throw new Exception("ID cannot be less than 0");
if (string.IsNullOrEmpty(FirstName))
throw new Exception("First Name cannot be empty");
this.ID = ID;
this.FirstName = FirstName;
}
}
Option 2
public class Customer{
public int ID { get; set; }
public string FirstName { get; set; }
public Customer(int ID, string FirstName){
this.ID = ID;
this.FirstName = FirstName;
}
public List<string> Validate(){
List<string> ErrorMessages = new List<string>();
if (ID < 0)
ErrorMessages.Add("ID cannot be less than 0");
if (string.IsNullOrEmpty(FirstName))
ErrorMessages.Add("First Name cannot be empty");
return ErrorMessages;
}
}