开发者

BL Services: Exception or Method Result?

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 re开发者_开发知识库sult = 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜