BL Services: Exception or Method Result?

北城以北 提交于 2019-12-22 09:47:53

问题


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
}

回答1:


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.




回答2:


First of all, the IoC.Resolve<IMyBLService>() is actually a very bad usage of IoC container, you should inject your dependencies, not resolve them. I know that's not the point of the question, but it's worth mentioning.

As for Exception vs method result, it depends. The standard way to handle this is with Exceptions, however there are scenarios where it is cleaner and less cumbersome to return result instead. For example, I very often use operation results, because I have a very specific requirements for throwing non-domain related exceptions out of my SOA layer, so I would need to catch a domain-related exception just to create a new one. It wasn't logical, it wasn't readable, it affected performance, so we switched to results with a little bit of infrastructural sugar.

Another thing worth mentioning is that Exceptions tend to be a PITA when you need to run and return results of all your validation, without braking on first invalid rule.



来源:https://stackoverflow.com/questions/7139831/bl-services-exception-or-method-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!