vkhorikov / CSharpFunctionalExtensions

Functional extensions for C#
MIT License
2.47k stars 305 forks source link

Proposal: Ensure `null` with `Maybe` #571

Open DerStimmler opened 2 months ago

DerStimmler commented 2 months ago

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

vkhorikov commented 1 week ago

Yeah, sounds useful enough. Feel free to submit a PR. Can't think of a better name than ToInvertedResult either :)