BL服务:异常或方法结果?异常、结果、方法、BL

2023-09-04 02:50:48 作者:Review 旧爱

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

V1:

 尝试
{
    VAR的服务= IoC.Resolve< IMyBLService>();
    service.Do();
}
赶上(BLException前)
{
   //处理异常
}
 

V2:

  VAR的服务= IoC.Resolve< IMyBLService>();
VAR的结果= service.Do();
如果(!result.Success)
{
   //处理异常
}
 

解决方案

例外的是在我看来更好。我认为,DDD code是首要良好的面向对象的code。而关于在面向对象的语言使用异常VS返回codeS的争论主要是结束了。在DDD方面,我看到使用异常以下优点:

他们强迫调用code来处理它们。异常不要让客户端code忘记了错误。调用code可以完全忘记检查 result.Success

既投掷和处理code是更具可读性,自然,简单的在我看来。没有IFS,没有多重return语句。无需弯曲你的域名服务,以公开为行动。

DDD在我看来是所有关于使用纯面向对象的语言来恩preSS具体的业务问题,并保持基础设施出尽可能多的。创建OperationResult级(ES)似乎过于基础设施和通用对我来说特别是当语言已经支持例外。

域对象将即使其仅用于检查参数抛出异常反正。所以他很自然地使用相同的机制域服务。

这也可能是值得考虑的设计本身,也许有一种方法可以不进入错误状态摆在首位?比如全班的验证错误条件可以通过使用值对象,而不是原始的字符串而被淘汰整数。

DDD是一种方法,一套指引,所以不存在正确的方式。该书从来没有提到直接这个问题,但code的片段和示例项目使用例外情况。

紧急 成都专科注意,学历落户最后15天

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
}

解决方案

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:

they force calling code to handle them. Exception don't let client code forget about the error. Calling code can simply forget to check for result.Success.

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 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.

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 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.