views:

41

answers:

1

I have an employee class in my application. The constructor for the class takes an employee ID. The way I try to check if the employee ID is valid is something like this

Employee emp = new Employee("E11234");
if (emp.IsValid())
{
    // do whatever is required
}
else
{
    // show an error message
}

In the constructor, I try to access the database and if I can retrieve records, I fill the values for the private members, else if no records exist, I set the isValid property to false.

Is this a correct way of achieving what I want to or is there a better method?

+2  A: 

You should separate the database access from your entity class (Employee). One option for separation is to use Repository-pattern for loading and saving the employee. The repository is responsible for accessing your database and the employee doesn't have to worry about where it came from or where you're going to store it.

There's many good tutorials available on using a repository and here in Stackoverflow we have a good question about this topic. When using a repository, your code would look like more like this:

Employee emp = EmployeeRepository.GetById("E11234");
if (emp.IsValid())
{ 
   do whatever is required 
}
else {     
  // show an error message
}

About the validation, your employee-class should not hit the the database in that one either. You could create a EmployeeValidator-class with a Validate-method, which then does all the required validation.

My best advice is that you should try to keep your entities away from your infrastructure.

Mikael Koskinen
should EmployeeRepository also be responsible for validation or should there be another class as you suggested? Is there a reason to separate the validation from the EmployeeRepository class?
TP
@TP. You should probably expect the repository to return a valid object or `null`, so your validation can be a simple `if (emp!=null)` in this case. An alternative is that your repository will throw an exception if the employee wasn't found, in which case you wrap the call into a try/catch block
Mark H