In a project I am working on we load various entities from the database, do some work then attempt to save the resulting entities.
If saving the result is not successful, we return a Result object containing any errors. If it is successful, we return Success = true
& Messages = new string[0]
and don't use it ever again in the rest of the method.
public class Result
{
public bool Success {get; set;}
public IEnumerable<string> Messages { get; set;}
}
public class Entity
{
public IEnumerable<Things> Things {get; set;}
public IEnumerable<MoreThings> MoreThings { get; set;}
public IEnumerable<EvenMoreThings> YouGetWhereThisIsGoing {get; set;}
}
public async Task<Result> DoSomeWork(...)
{
Entity x = await myService.LoadAsync(identifierParam).ConfigureAwait(false);
... do some work with x ...
var saveResult = await myRepoService.SaveAsync(x.Things).ConfigureAwait(false);
if (!saveResult.Success) return saveResult;
saveResult = await myOtherRepo.SaveAsync(x.MoreThings).ConfigureAwait(false);
if (!saveResult.Success) return saveResult;
saveResult = await yetAnotherRepo.SaveAsync(x.YouGetWhereThisIsGoing).ConfigureAwait(false);
if (!saveResult.Success) return saveResult;
... assuming all goes well ...
return new Result { Success = true, Messages = new string[0] };
}
This has been extremely simplified, but in this example is reusing the saveResult
actually accomplishing anything/more readable than
var thingSaveResult = ...SaveAsync(x.Things)
...
var moreThingsSaveResult = ...SaveAsync(x.MoreThings)
...etc.?