ardalis / Result

A result abstraction that can be mapped to HTTP response codes if needed.
MIT License
866 stars 107 forks source link

Allowing Result to be partial #205

Open tobysmith568 opened 1 month ago

tobysmith568 commented 1 month ago

Hey,

Would you consider modifying the Result<T> class to be marked with partial?

I've built up a small little arsenal of extension methods for Result<T> in my codebase (that are probably too specific to hold value in your repo) however sometimes these extension methods would fit better as traditional static methods.

My current example is an attempt to get around a common pattern I find myself using where I need to use an if to return either a Success or a NotFound based on the nullability of a variable:

if (returnValue is null)
  return Result<ReturnValue>.NotFound();

return Result<ReturnValue>.Success(returnValue);

I'm currently getting around this by using a OrNotFound extension method:

// Implementation
public static class ResultExtensions
{
    public static Result<T> OrNotFound<T>(this Result<T?> value) =>
        value.Value is null ? Result<T>.NotFound() : Result<T>.Success(value.Value);
}

// Usage
return Result<ReturnValue?>.Success(returnValue).OrNotFound();

This works because it turns the Result<T?> (nullable) into a Result<T> (non-nullable), however I'd probably prefer something like this:

namespace Ardalis.Result
{
    public partial class Result<T>
    {
        public static Result<T> SuccessOrNotFound(T? value) =>
            value is not null ? Result<T>.Success(value) : Result<T>.NotFound();
    }
}

By marking Result<T> as partial I'd able to create my own static method without the need to inspect the .Value of a Result<T> in order to return either a Success or NotFound.

Thanks, let me know what you think :)