Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods of simplifying ugly nested if-else trees in C#

Tags:

c#-3.0

Sometimes I'm writing ugly if-else statements in C# 3.5; I'm aware of some different approaches to simplifying that with table-driven development, class hierarchy, anonimous methods and some more. The problem is that alternatives are still less wide-spread than writing traditional ugly if-else statements because there is no convention for that.

What depth of nested if-else is normal for C# 3.5? What methods do you expect to see instead of nested if-else the first? the second?

if i have ten input parameters with 3 states in each, i should map functions to combination of each state of each parameter (really less, because not all the states are valid, but sometimes still a lot). I can express these states as a hashtable key and a handler (lambda) which will be called if key matches.

It is still mix of table-driven, data-driven dev. ideas and pattern matching.

what i'm looking for is extending for C# such approaches as this for scripting (C# 3.5 is rather like scripting) http://blogs.msdn.com/ericlippert/archive/2004/02/24/79292.aspx

like image 456
rudnev Avatar asked Oct 24 '09 16:10

rudnev


People also ask

How do you simplify nested if statements?

To combine the logic of nested ifs into a single if statement we use C#'s logical AND operator ( && ). This operator combines two Boolean expressions into a single true/false value. When the value on its left and the value on its right are both true , && returns true as well.

How do you refactor multiple If else?

So, how do you refactor multiple nested if statements? The easiest possible way is to use guard clauses. A guard clause is an if statement that checks for a condition and favors early exit from the current method. If the condition is satisfied, the if block returns from the method.

Which of the following can replace the multiple if conditions in C#?

You can use switch statement instead of multiple if statements.


2 Answers

Good question. "Conditional Complexity" is a code smell. Polymorphism is your friend.

Conditional logic is innocent in its infancy, when it’s simple to understand and contained within a few lines of code. Unfortunately, it rarely ages well. You implement several new features and suddenly your conditional logic becomes complicated and expansive. [Joshua Kerevsky: Refactoring to Patterns]

One of the simplest things you can do to avoid nested if blocks is to learn to use Guard Clauses.

double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};  

The other thing I have found simplifies things pretty well, and which makes your code self-documenting, is Consolidating conditionals.

double disabilityAmount() {
    if (isNotEligableForDisability()) return 0;
    // compute the disability amount

Other valuable refactoring techniques associated with conditional expressions include Decompose Conditional, Replace Conditional with Visitor, Specification Pattern, and Reverse Conditional.

like image 144
Ewan Todd Avatar answered Oct 26 '22 12:10

Ewan Todd


There are very old "formalisms" for trying to encapsulate extremely complex expressions that evaluate many possibly independent variables, for example, "decision tables" :

http://en.wikipedia.org/wiki/Decision_table

But, I'll join in the choir here to second the ideas mentioned of judicious use of the ternary operator if possible, identifying the most unlikely conditions which if met allow you to terminate the rest of the evaluation by excluding them first, and add ... the reverse of that ... trying to factor out the most probable conditions and states that can allow you to proceed without testing of the "fringe" cases.

The suggestion by Miriam (above) is fascinating, even elegant, as "conceptual art;" and I am actually going to try it out, trying to "bracket" my suspicion that it will lead to code that is harder to maintain.

My pragmatic side says there is no "one size fits all" answer here in the absence of a pretty specific code example, and complete description of the conditions and their interactions.

I'm a fan of "flag setting" : meaning anytime my application goes into some less common "mode" or "state" I set a boolean flag (which might even be static for the class) : for me that simplifies writing complex if/then else evaluations later on.

best, Bill

like image 37
BillW Avatar answered Oct 26 '22 12:10

BillW