Question

I am using the Repository Pattern for my application. I have a class User. User is identified by Email. The UserRepository contains a method CreateUser(User user). There is a business rule saying that users should have a unique Email.

I want to implement a transaction which first checks whether an email is in use and if not, the user is created. Where should I put this code which is responsible for checking the uniqueness of the Email?

This is definitely a business rule; it is business logic. I think it is not correct to put this check in my UserRepository implementation.

Was it helpful?

Solution

This sort of thing typically goes in either (1) a service or (2) directly into the schema as a database constraint (and frequently both).

Using a service, you don't access the Repository directly from client code; you call a service which does the useful operations for you.

For example, something like:

public class UserService : ... {
  private Repository<User> _userRepository;

  public void CreateUser(User u) {
    // Verify that the user's email is unique.
    if ( ... ) {
      _userRepository.Create(u);
    }
  }
}

OTHER TIPS

If you're building an application large enough to warrent a repository pattern then you'll want to put this validation as close to the data as possible, probably a database constraint such as a unique index/key. This prevents situations of bugs leaking into code later due to corrupt data.

Assuming you're using a database for storage, you should definitely add a unique constraint on the e-mail column in the database.

Check out this excellent article on Simple Talk:

Five Simple Database Design Errors You Should Avoid

See in Section 4:

Enforcing Integrity via applications

Proponents of application based integrity usually argues that constraints negatively impact data access. They also assume selectively applying rules based on the needs of the application is the best route to take. .....

The solution is simple.

Rely on nothing else to provide completeness and correctness except the database itself. By nothing, I mean neither users nor applications external to the database.**

So in your case - a unique constraint on your e-mail column should really be modelled in the database. That's the best place to put that piece of business logic, and will save you from a lot of grief in the long run.

Marc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top