MrDave1999 / SimpleResults

A simple library to implement the Result pattern for returning from services
https://mrdave1999.github.io/SimpleResults
MIT License
103 stars 2 forks source link

Why it was decided to create different extension methods called ToActionResult? #62

Closed MrDave1999 closed 6 months ago

MrDave1999 commented 6 months ago

See https://mrdave1999.github.io/SimpleResults/api/SimpleResults.ResultExtensions.ToActionResult.html

MrDave1999 commented 6 months ago

A single method called ToActionResult could have been created that returned an ActionResult, however, this would allow the consumer to do something like this:

[Route("api/[controller]")]
public class UserController
{
    private readonly UserService _userService;
    public UserController(UserService userService) => _userService = userService;

    [HttpGet("{id}")]
    public ActionResult<int> Get(string id)
    {
        Result<User> result = _userService.GetById(id);
        ActionResult actionResult = result.ToActionResult();
        return actionResult;
    }
}

We do assume that ToActionResult returns an ActionResult, so the consumer can add any type of return value in the controller action and the compiler will not generate any compiler error. This happens because there is an implicit conversion from ActionResult to ActionResult{TValue}.

Therefore, it has been decided to create different ToActionResult methods that returns ActionResult{TValue} to obtain more help from the compiler.

For example,

[Route("api/[controller]")]
public class UserController
{
    private readonly UserService _userService;
    public UserController(UserService userService) => _userService = userService;

    [HttpGet("{id}")]
    public ActionResult<Result<User>> Get(string id)
    {
        Result<User> result = _userService.GetById(id);
        ActionResult<Result<User>> actionResult = result.ToActionResult();
        return actionResult;
    }
}

In that case, changing the return value type to ActionResult<int> should generate a compilation error.