Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone think of an elegant way of reducing this nested if-else statement?

Tags:

c#

if (Request.QueryString["UseGroups"] != null)
{
  if (Request.QueryString["UseGroups"] == "True")
  {
    report.IncludeGroupFiltering = true;
  }
  else
  {
    report.IncludeGroupFiltering = false;
  }
}
else
{
  report.IncludeGroupFiltering = false;
}
like image 461
MetaGuru Avatar asked Jul 30 '10 20:07

MetaGuru


People also ask

Are nested if-else statements Bad?

The problem only occurs when you have many nested in many and so it can become hard to read and you may forget something, but that's readability, there is nothing wrong in the logic for using nested if statements.

How do you reduce nested if statements in Java?

getSelection() != null can however often be transformed to reduce the nesting. Consider some kind of if (freqChooser. getSelection() == null) { return ... } or similar possibilities.


1 Answers

Simply a single check:

report.IncludeGroupFiltering = Request.QueryString["UseGroups"] == "True";

There's no need to evaluate Request.QueryString["UseGroups"] twice - it can only be equal to "True" if it's non-null, and the comparison will work perfectly well (and return false) if it is null.

Any solutions still doing two operations are over-complicating matters :)

like image 177
Jon Skeet Avatar answered Nov 09 '22 18:11

Jon Skeet