Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Ensure null with Maybe #571

Open
DerStimmler opened this issue Sep 30, 2024 · 0 comments
Open

Proposal: Ensure null with Maybe #571

DerStimmler opened this issue Sep 30, 2024 · 0 comments

Comments

@DerStimmler
Copy link
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant