DDD:存储库可以返回布尔值吗?
存储库可以根据它(虚拟)包含的对象返回布尔值吗?
例如:
if (userRepository.checkCredentials(username, password))
{
// ...
或者以详细的方式执行此操作是否是更好的方法:
user = userRepository.findByUsername(username);
if (user != null && user.checkPassword(password)) {
{
// ...
Is it ok for a Repository to return boolean values based on objects it (virtually) contains?
For example:
if (userRepository.checkCredentials(username, password))
{
// ...
Or is it a better approach to do it the verbose way:
user = userRepository.findByUsername(username);
if (user != null && user.checkPassword(password)) {
{
// ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来更像是一个规范,不是吗?
过去,我通过规范来完成此操作,因此我可以清楚、简单地进行检查以供我的代码使用。
但是,最近,我使用一项服务完成了这项工作,并根据他们未进行身份验证的原因构建结果。所以,像这样:
Sounds more like a specification doesn't it?
In the past, I have done this with a specification, so I can clearly and simply have that check around for my code to use.
But, recently, I did this with a service that does the work, and builds a result based on why they didn't authenticate. So, something, like this:
我认为从存储库返回布尔值是可以的,但前提是该方法涉及此存储库中的所有对象。存储库通常公开类似集合的接口。例如,
users.IsEmpty()
或users.IsNameUnique("jdoe")
似乎合乎逻辑,因为它们需要访问整个集合。在您的场景中,仅按名称查找用户是可以分配给存储库的责任。检查密码是否有效似乎不太适合存储库。因此,第二种更详细的方法对我来说似乎更好。
或者,您可以在域中拥有专用的身份验证器接口,并在数据访问层中实现(类似于存储库的实现方式)。或者Authenticator可以成为内部使用存储库的域服务。身份验证器还可以区分“未找到用户”或“密码无效”,这可能具有不同的业务含义。
I think it is OK to return boolean from a repository but only if the method involves all the objects in this repository. Repository usually exposes collection-like interface. For example
users.IsEmpty()
orusers.IsNameUnique("jdoe")
seem logical because they need access to the whole collection.In your scenario, only finding user by name is the responsibility that can be assigned to the repository. Checking whether password is valid or not does not seem like a good fit for repository. So the second, more verbose, approach seems better to me.
Alternatively you can have a dedicated Authenticator interface in your domain and implementation in data access layer (similarly to how repositories are implemented). Or Authenticator can become a domain service that uses repository internally. Authenticator can also tell between 'user not found' or 'password invalid' which would probably have different business meaning.