Hi Scott,
Thank you for your reply. The first link are interesting about validation. But I'm not sure I would like to throw an exception if one of the business rules are broken.
I haven't used the Specification pattern yet but I will take a closer look at it.
I have included a quick example of how I would like to solve this "problem" about validation of business rules. I would appriciate to know what you think about this approch.
ValidationError.cs contains validation error message.
Code:
public class ValidationError
{
public string Property { get; private set; }
public string Message { get; private set; }
public ValidationError(string property, string message)
{
Property = property;
Message = message;
}
}
User.cs This is the user model.
Code:
public class User
{
public string Username { get; set; }
public string Password { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public List<ValidationError> ValidationErrors { get; set; }
public User()
{
ValidationErrors = new List<ValidationError>();
}
public bool Validate()
{
ValidationErrors.Clear();
ValidationRules();
return ValidationErrors.Count == 0;
}
private void ValidationRules()
{
if (String.IsNullOrEmpty(Username))
ValidationErrors.Add(new ValidationError("Username", "You must enter a username"));
}
}
UserService.cs The CreateUser mothod validates the user before saving and returning false if the validation contains errors.
Code:
public class UserService
{
public bool CreateUser(User user)
{
if (!user.Validate())
return false;
// Insert user to database.
return true;
}
}
Here follows an example of how I create a user.
Code:
User user = new User();
UserService service = new UserService();
if (service.CreateUser(user))
{
Response.Write("The user was successfully created.");
}
else
{
Response.Write(user.ValidationErrors[0].Message);
}
Here I can use an if-statement that tells me if the creation fails and get the get the validation messages.
If I instead throw exceptions if validation fails I need to place the call of CreateUser in a try catch block to catch the validation errors. This is for me harder to remember when I need to create a user instead of just using an if-statement. What is your opinion about this approch?
Cheers
Erik