randomThought
randomThought

Reputation: 6393

Correct approach to handle data verification

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?

Upvotes: 2

Views: 134

Answers (1)

Mikael Koskinen
Mikael Koskinen

Reputation: 12906

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.

Upvotes: 2

Related Questions