Search code examples
c#if-statementmaintainability

Reduce complexity, increase maintainability of multiple If-Else statements?


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?


Solution

  • You could use the ternary ?: operator:

    ClassOne varOne = condition == null ? mammal : reptile;
    ClassTwo varTwo = diffCondition == null ? dog : cat;