0

I have a method that I am trying to reduce the complexity and increase the maintainability. It contains multiple if-else statements, all setting different information as below:

ClassOne varOne = null;
if (condition == null)
{
    varOne = mammal;
}
else
{
    varOne = reptile;
}


ClassTwo varTwo = null;
if (diffCondition == null)
{
    varTwo = dog;
}
else
{
    varTwo = cat;
}

I have a lot more that 2 statements, above is an example. Is there a way of reducing the complexity of this one method?

Dmitry
  • 13,797
  • 6
  • 32
  • 48
pcoul
  • 127
  • 1
  • 1
  • 7
  • 3
    [ternary operator](http://msdn.microsoft.com/en-us/library/ty67wk28.aspx)? – oblitum Nov 13 '14 at 17:05
  • 1
    If the conditions are always in the form `if(x == null) ... else`, you could use the [ternary operator](http://msdn.microsoft.com/en-us/library/ty67wk28.aspx) `?`. For example, `ClassOne varOne = condition == null ? mammal : reptile;`. – hunch_hunch Nov 13 '14 at 17:06
  • 1
    If they are always binary a ternary may be fine, otherwise perhaps a `Dictionary` would be in order. – Mgetz Nov 13 '14 at 17:19

1 Answers1

3

You could use the ternary ?: operator:

ClassOne varOne = condition == null ? mammal : reptile;
ClassTwo varTwo = diffCondition == null ? dog : cat;
Dmitry
  • 13,797
  • 6
  • 32
  • 48