Sorry if the title isn’t worded the best.
My UserRepository has a method that will create a new User. Where should my validation go to check to make sure all the fields are that are needed to create the user are filled in: Username, Password, Email and Created. If any of the values are null then the insert will throw an error.
public class UserRepository : IRepository<User>
{
public DbConnection Connection { get; set; }
public UserRepository(DbConnection connection)
{
this.Connection = connection;
}
public void Create(User user)
{
string sql = "INSERT INTO [dbo].[User] (Username, Password, Email, Created) VALUES (@Username, @Password, @Email, @Created)";
using (DbCommand command = new SqlCommand())
{
command.Connection = this.Connection;
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("@Username", user.Username));
command.Parameters.Add(new SqlParameter("@Password", user.Password));
command.Parameters.Add(new SqlParameter("@Email", user.Email));
command.Parameters.Add(new SqlParameter("@Created", user.Created));
command.ExecuteScalar();
}
}
}
Should my create method actually check the values here? I feel it should not do the validation here, but I’m not sure the appropriate place for separation.
It’s always a good idea to keep business logic separate from data access code. It makes business logic code more readable and maintainable. “Validation” here is part of business logic, therefore I recommend handling it at an upper layer. Think of creating “service” classes which receive input, validate them and perform DB access through repository.
Let’s say your scenario is “create a new user through registration”. It makes sense to have a
RegistrationServiceclass with aCreateUsermethod.There is another option of using
Userclass itself for point of validation. You can make User class immutable, have it receive all parameters in constructor and validate them during construction. Therefore you rule out the possibility of having an “invalid” instance. Any function which receivesUseras a parameter actually is guaranteed to receive a “valid User” instance.As a final note, it helps to make it a habit to check for null arguments and throw
ArgumentNullExceptioninpublicfunctions, regardless of validation.