0

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!

4

2 回答 2

3

我肯定会选择第二种选择:

  • 正如您所提到的,它避免了对服务的 1 次调用
  • 它只使用一种创建员工的方法来保持您的服务界面清洁
  • 从事务的角度来看,它是一致的(异常意味着“事务失败”)。请记住,验证不仅是导致交易失败的众多原因之一。
  • 想象一下您的验证约束不断发展(例如:其他员工属性......),您不会想让您的所有实现仅为此而发展。

需要记住的一点:确保让你的异常足够详细,以清楚地识别失败的原因。

于 2012-05-11T23:19:35.850 回答
1

如果“演示”层的真正意思是演示,那么您不应该在该层创建新员工。您应该只准备在 HTTP 响应对象中清晰呈现的任何数据。

通常,考虑此类问题的一个好方法是考虑如果被命令行程序调用,您的服务对象应该做什么:

> createEmployee allison.brie@awesome.com
  Error! 'allison.brie@awesome.com' is already registered.

其中有一些终端管理层调用该服务。该服务会做一些事情来实现另一个用户使用相同的电子邮件,并抛出一个适当的异常(即DuplicateUserException)。然后终端管理层解释该异常并打印出来"Error! " + exception.getMessage();

也就是说,请注意您的两个选项实际上是相同的选项。您的服务仍必须查询数据库中的重复项。虽然这是“验证”,但它不是输入验证。输入验证意味着检查它是否是有效的电子邮件地址。(是否有“@”符号和有效的 TLD?)

于 2012-05-11T23:19:08.730 回答