Search code examples
.netarchitecturedomain-driven-designbusiness-logicn-tier-architecture

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 result = service.Do();
if (!result.Success)
{
   //Handle exception
}

Solution

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