0

Is this a good code pattern in ASP.NET Core Razor Pages, for private methods to return IActionResult to the calling handler?

// Public handler

public IActionResult OnGet()
{
    var result = SetupPage();
    if (result != null)
        return result;

    // do some work

    return Page();
}

// Private methods

private IActionResult SetupPage()
{
    if (allValid)
    {
        // call method to do some work
        var result = DoSomething();
        if (result != null)
            return result;

        // do some more work
        return null;
    }
    else
    {
        return Return(abcUrl);
    }
}

private IActionResult DoSomething()
{
    if (someCondition)
    {
        // do some work
        return null;
    }
    else
    {
        return Return(xyzUrl);
    }
}

I feel like result checks and redirection in each method is not elegant. If so, what's a good alternative?

  • doesnt look good. why are you doing it? – Ewan Oct 26 '19 at 10:15
  • 1
    Also, you could just reorganize the code so that you don't return nulls. Your logic is: delegate to some other method, then if the result is null, do something else. Why not extract that "something else" part into its own method? Pull the conditionals out, put them in the caller, and decide which private method to call there. Then just assume in your private methods that the conditions have been met, and remove the null path completely. If you need to do some work w/ out returning anything, extract that into a void method. – Filip Milovanović Oct 27 '19 at 4:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.