4
\$\begingroup\$

It would be nice to simplify the verbosity of this:

public IActionResult Get(int id)
{
    var movie = context.GetMovie(id);

    if (movie != null)
    {
        return Ok(movie);
    }
    else
    {
        return NotFound();
    }
}

with something like this:

public IActionResult Get(int id)
{
    var movie = context.GetMovie(id);
    return (movie != null) ? Ok(movie) : NotFound();
}

Of course, this is an error because the two objects in the ternary must be of the same type, not just sharing the same inheritance (or is this incorrect?).

The closest I can get is to explicitly cast one of the values as an IActionResult:

return (movie != null) ? Ok(movie) : (IActionResult) NotFound();

Is there a better option?

\$\endgroup\$
  • \$\begingroup\$ This should be applicable to both ASP.NET and ASP.NET Core - right? \$\endgroup\$ – Erik Anderson Sep 1 '17 at 17:59
  • 1
    \$\begingroup\$ Looks very readable the way it is to begin with. The if block returns so you could get rid of the else. \$\endgroup\$ – James Sep 2 '17 at 2:13
  • \$\begingroup\$ The two methods both return objects that inherit from StatusCodeResult. If you use an intermediate variable like StatusCodeResult result = (movie == null) ? NotFound() : Ok(); does it work? \$\endgroup\$ – RubberDuck Sep 3 '17 at 1:14
  • \$\begingroup\$ As an aside, I agree with James that the code you have is perfectly fine the way it is. It's clear and readable as is. Shorter isn't necessarily better. \$\endgroup\$ – RubberDuck Sep 3 '17 at 1:15
2
\$\begingroup\$

So, as mentioned in comments: the code is readable and there are no issues with "verbosity". And as mentioned you can get rid of else statement, also it's a good habit to exclude "bad" cases at first.

public IActionResult Get(int id)
{
    var movie = context.GetMovie(id);

    if (movie == null)
    {
        return NotFound();
    }

    return Ok(movie);
}
\$\endgroup\$
0
\$\begingroup\$

If Ok returns null if you pass a null as argument you can simplify it like this

public IActionResult Get(int id, Context context) => Ok(context.GetMovie(id)) ?? NotFound();
\$\endgroup\$
  • \$\begingroup\$ Oh, now that's interesting! \$\endgroup\$ – Erik Anderson Sep 8 '17 at 16:54

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.