CSharpFunctionalExtensions icon indicating copy to clipboard operation
CSharpFunctionalExtensions copied to clipboard

Proposal: Ensure `null` with `Maybe`

Open DerStimmler opened this issue 1 year ago • 0 comments

Currently, the ToResult method on Maybe returns a success result if the Maybe has a value, and a failure result if there is no value.

But what if it should be the other way around?


Lets say I want to create a report, but only if no report already exists.

Right now I would probably do something like this:

await Result
      .Success()
      .Map(() => service.FindAsync(id)) //returns Report?
      .Ensure(report => report is null, "There is already a report available.")
      .Tap(_ => service.CreateReport())
      ...

But this comes with some overhead because I have to start the chain with an empty success result to then map the nullable value and ensure its null using the Ensure method.

I think it would be more appropriate and compact to use Maybe and its ToResult method since I'm dealing with a nullable.

But to keep the chain running if the Maybe has no value, I basically need an inverted ToResult method that returns a success result if there is no value. E.g:

await Maybe
      .From(service.FindAsync(id))
      .ToInvertedResult("There is already a report available.") //returns success result if Maybe has no value, otherwise returns failure result with error message
      .Tap(() => service.CreateReport())
      ...

What do you think about this addition?

ToInvertedResult is just an example name because I can't think of anything better. 😄

DerStimmler avatar Sep 30 '24 20:09 DerStimmler