I have this scenario in my 3-tier app with a Service Layer that serves to a MVC presentation layer:
I have an operation that creates, for example, an Employee whose email must be unique in the set of Employees. This operation is executed in the MVC presentation layer through a service.
How do I manage the intent to create a Employee whose email is already registered in the Database for another Employee?
I am thinking in 2 options:
1) Have another operation that queries if there’s an Employee with the same email given for the new Employee.
2) Throw an exception in the service CreateEmployee for the duplicate email.
I think it is a matter of what I think is best or most suitable for the problem.
I propose the 1) option because I think that this is a matter of validation.
But the 2) option only needs 1 call to the service, therefore its (?) more efficient.
What do you think?
Thanks!
If by ‘Presentation’ layer you really mean presentation, you should not be creating a new employee in that layer. You should only be preparing any data to be cleanly presented in the HTTP response object.
Generally a good way to think of this sort of problem is to consider what your service objects should do if called by a command-line program:
In this there is some terminal management layer that calls the service. The service does something to realize there is another user with the same email, and throws an appropriate exception (ie
DuplicateUserException). Then the terminal management layer interprets that exception and prints out"Error! " + exception.getMessage();That said, note that your two options are actually the same option. Your service must still query the database for the duplicate. While this is ‘validation’ it is not input validation. Input validation means checking to see if it’s a valid email address. (Is there an ‘@’ symbol and a valid TLD?)