BL 服务:异常还是方法结果? [英] BL Services: Exception or Method Result?

查看:23
本文介绍了BL 服务:异常还是方法结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好的方法是什么?为什么?

What is the best way and why?

V1:

try
{
    var service = IoC.Resolve<IMyBLService>();
    service.Do();
}
catch(BLException ex)
{
   //Handle Exception
}

V2:

var service = IoC.Resolve<IMyBLService>();
var result = service.Do();
if (!result.Success)
{
   //Handle exception
}

推荐答案

在我看来,例外更好.我认为 DDD 代码首先是好的面向对象代码.关于在 OO 语言中使用异常还是返回代码的争论已经基本结束.在 DDD 上下文中,我看到使用异常的以下好处:

Exceptions are better in my opinion. I think that DDD code is first and foremost good object oriented code. And the debate about using exceptions vs return codes in OO languages is mostly over. In DDD context I see following benefits of using exceptions:

  • 它们强制调用代码来处理它们.异常不要让客户端代码忘记错误.调用代码可能会忘记检查 result.Success.

在我看来,抛出和处理代码都更具可读性、自然和简洁.没有'ifs',没有多个返回语句.无需将您的域服务弯曲为操作".

both throwing and handling code is more readable, natural and brief in my opinion. No 'ifs', no multiple return statements. No need to bend your Domain services to be exposed as 'operations'.

在我看来,DDD 就是使用纯面向对象的语言来表达特定的业务问题,并尽可能将基础设施排除在外.创建OperationResult"类对我来说似乎过于基础和通用,尤其是当语言已经支持异常时.

DDD in my opinion is all about using plain OO language to express specific business problems and keeping infrastructure out as much as possible. Creating 'OperationResult' class(es) seems too infrastructural and generic to me especially when language already supports exceptions.

域对象无论如何都会抛出异常,即使它只是为了检查参数.因此,对域服务使用相同的机制似乎很自然.

Domain objects will throw exceptions anyway, even if its only for checking arguments. So it seems natural to use the same mechanism for domain services.

设计本身也可能值得一看,也许有一种方法可以首先不进入错误状态?例如,可以通过使用 Value Objects 而不是原始字符串和整数.

It may also be worth looking at the design itself, maybe there is a way to not get into error state in the first place? For example the whole class of 'validation' error conditions can be eliminated by using Value Objects instead of primitive strings and ints.

DDD 是一种方法,一套指导方针,因此没有正确"的方法. 从未直接提及这个问题,但代码片段和示例项目使用异常.

DDD is an approach, a set of guidelines so there is no 'right' way. The book never mentions this issue directly but the code in snippets and sample project use exceptions.

这篇关于BL 服务:异常还是方法结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆