I have a fluent validation API that throws an exception when a supplied boolean result is false. This works fine.
I’d like to improve upon this by, instead of throwing an exception, providing some functionality to execute if the result is false, and then forcing the calling method to return. Example, the supplied functionality might new up a response, initialise it appropriately and return it.
Is doing this even possible? (I suspect not).
Work around seems to be something like initializing an out param (the response), and returning that from the calling method.
Desired:
Ensure.That(request.IsValid(), () => new Response { Errors = request.Errors }); //I want lambda to force containing method reeturn
As implemented:
Response response;
Ensure.That(request.IsValid(), r => new Response{Errors = request.Errors}, out response);
if (response.IsNotNull()) return response;
The calling method has to know to do it, basically. How you signal that is up to you – a return value, an
outparameter etc – but you can’t force it from the delegate itself other than with an exception (which could still be caught, of course).