3 Conditional Branching Alternatives to ‘If’ Statements

Konstantinos Gkizinos
Geek Culture
Published in
3 min readNov 6, 2022

Concepts and examples for creating conditional branching

Conditional branching is the execution or evaluation of a portion of code dependent on a condition, which is commonly performed using an if…else construct.

example:

if (Personishere)
{
sayHi()
}
else
{

Donothing();

}

sayHi() will get called if Personishere is true; otherwise Donothing() will be called.

Some in the programming world believe it should be deemed detrimental or a code smell. Regardless of the veracity of this argument, there may be situations in which it is not the ideal method to branch or when branching should be avoided entirely.

In this article, I’ll show you six alternatives toif...else

1. Switch Statement

The following is the structure of a switch statement:

The break statements are optional and will leave the switch block.

If a break is not used, execution will continue to the following case statement.

The switch function is handy for branching on a homogenous collection of values.

2. The Dynamic Dispatch

A dynamic dispatch is an alternative to utilizing if statements. This entails deciding the polymorphic method to invoke based on the type of an object.

Image from Jamie Bullock

Depending on the kind of object supplied to the handleShape method, a separate code path is followed. Because Shape is a Square in our example, the area is stored as 4.

This method can result in a lot more code, but there are certain advantages to using it instead of an if…else statement. This style is often suitable when the code already uses OOP; however, attempting to build branching to always utilize polymorphism appears to be overkill.

3. while loop

The syntax of the while loop is:

while (testExpression) {
// the body of the loop
}
image from Programiz

So, we can change the if statement with a while loop or a do…while loop

The do..while loop is similar to the while loop, but there is one significant distinction. The body of the do…while loop is run at least once. The test expression is only then evaluated.

The syntax of the do...while loop is:

do {
// the body of the loop
}
while (testExpression);

Example of converting an if statement to a while loop:

if example:

if (cond)
{
exec1();
}
if (!cond)
{
exec2();
}

When we change it to while:

while (cond) 
{
exec1();
break;
}
while (!cond)
{
exec2();
break;
}

Conclusion

Conditional branching adds complexity to a program.

Nested if and switch statements can make code less understandable and increase the likelihood of problems. Other types of branching might result in a codebase that is overengineered. If it is feasible to avoid branching entirely, this is frequently a suitable starting point.

--

--