Open In App

Avoiding elif and ELSE IF Ladder and Stairs Problem

Last Updated : 19 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

This article focuses on discussing the elif and else if ladder and stairs problem and the solution for the same in the C and Python Programming languages.

The ELIF and ELSE IF Ladder and Stairs Problem

There are programmers who shy away from long sequences of IF, ELSE IF, ELSE IF, ELSE IF , etc. typically ending with a final ELSE clause. In languages with ELSE IF or  elif syntax, the pattern is called an “ELSE IF ladder.” In languages without ELSE IF or elif , each conceptual ELSE IF is written as an IF placed within the  ELSE  part of its predecessor. With indenting, it looks like descending an upside-down staircase.

  • This forms an undesirable, hard-to-read, worse-to-enhance, error-prone programming structure. 
  • With indenting, the staircase code falls off the right side of the screen. 
  • For some programmers, the problem is esthetics, while others worry about maintainability. 
  • Sometimes, the syntax genuinely gets in the way of expressing the logic that needs to express. 

Fundamentally this pattern expresses both prioritization and a short-circuiting: 

  • The prioritization is that statements are processed only for the first TRUE among a set of conditions. 
  • The short-circuiting is that after the first condition is found to be true, no further test condition expressions are even evaluated. This matters because condition expressions may invoke some functions, such as IF (42 < somefunction( x ) ). . . , where some functions might be stateful and have side-effects. 

Any alternative must maintain these semantics. Furthermore, sometimes there are statements that need to be executed only if some prior conditions fail, but need to execute for all the later conditions. 

Example: 

C




// Many people find this code 
// undesirable to work with.
if (a < b) 
{
    // a<b statements
}
else if (b < c) 
{
    // b<c statements
}
else if (c < d) 
{
    // Statements before every 
    // remaining possibility
    a = 45;
    
    // c<d statements
}
else if (d < e) 
{
    // Statements before every 
    // remaining possibility
    a = 45;
    
    // d<e statements
}
else if (e < f) 
{
    // Statements before every 
    // remaining possibility
    a = 45;
    
    // e<f statements
}
else 
{
    // Statements before every 
    // remaining possibility
    a = 45;
    
    // else statements
}


Python3




# Many people find this code 
# undesirable to work with.
  
if (a < b):
    # a<b statements
      
elif (b < c):
    # b<c statements
      
elif (c < d):
    # statements before every 
    # remaining possibility
    a = 45
      
    # c<d statements
      
elif (d < e):
    # statements before every 
    # remaining possibility
    a = 45
      
    # d<e statements
      
elif (e < f):
    # statements before every 
    # remaining possibility
    a = 45
      
    # e<f statements
      
else:
    # statements before every 
    # remaining possibility
    a = 45
      
    # else statements
      
# end of IF-ELIF-ELSE   
pass  
  
# Contributed by David A. Kra


Note that this repetition of statements that apply to each of the later possibilities ( a = 45 ) violates the “Don’t Repeat Yourself” (DRY) principle. Any change must be repeated after each condition.

Two-step Approach To Eliminate ELSE IF and ELSE 

Instead of the ELSE IF and ELSE code above, the following approach eliminates the need for them, while keeping the prioritization and short-circuiting semantics:

  1. Place a set of independent IF statements within a single-iteration loop.  Do not use any ELSE IF or ELSE syntax. 
  2. Add a loop exiting statement as the last of the statements within each  IF.  BREAK is preferred to  CONTINUE. The python code offers a for and a while version of the loop. BREAK must be used with the while version of the loop.

Example:

C




// This is the ELSEless equivalent.
do 
  // This is a one pass WHILE loop.
    if (a < b) 
    {
        // a<b statements
        break;
    }
    if (b < c) 
    {
        // b<c statements
        break;
    }
  
    // Statements for every remaining 
      // possibility
    a = 45;
  
    // More conditions
    if (c < d) 
    {
        // c<d statements
        break;
    }
    if (d < e) 
    {
        // d<e statements
        break;
    }
    if (e < f) 
    {
        // e<f statements
        break;
    }
  
    // else statements
    q = 75;
  
    // break unnecessary. 
    // Already at end of loop.
} while (0); 
  
// Once was enough. Do not repeat it.


Python3




# This is the ELSEless equivalent.
  
# for version # !!!! Use any one and 
# only one value in the iteration set. !!!!
# forversion="""for i in ("once - elseless"):"""
  
# while version # !!!! requires a BREAK 
# at the bottom !!!!
# whileversion="""while(True):"""
while (True):
    
     if (a < b):
         # a<b statements
         break  
            
     if (b < c):
         # b<c statements
         break   
  
     # statements for every remaining 
     # possibility indenting aligns
     # with the if's above
     a = 45
      
     if (c < d):
          # c<d statements
          break   
            
     if (d < e):
          # d<e statements
          break   
            
     if (e < f):
          # e<f statements
          break   
       
     # else statements
     # indenting aligns with the if's above
     q = 75
        
     # for version: break unnecessary. 
     # Already at end of one-pass loop.
     # while version: break absolutely 
     # required for the while version
     break # required for the while version
      
pass  # past end of else-less IF-ELIF-ELSE
  
# Contributed by David A. Kra


Explanation: We rarely, if ever, intentionally code a loop that will always be used for exactly one iteration, but here we do that. Most programming languages provide a loop control statement, such as BREAK to exit a loop completely, or CONTINUE, to jump to the loop’s next iteration. However, in this one-pass loop usage, there will not be and must not be any next iteration. 

This solution exploits these iteration statements in place of ELSE IF and ELSE. The BREAK, or CONTINUE statement causes all further statements inside the loop to be bypassed. When the loop is specified so as to have only one iteration, even a CONTINUE statement leads to exiting the loop. 

In the code sample, either CONTINUE or BREAK will work with the C version or the for loop version in python. The while loop python version requires the use of the break statement, including one after the final else-equivalent statements. 

Also, in between the IF statements, there can be additional statements that execute before testing any of the later conditions.  

Processing Cost or Overhead: The python version does experience the minimal overhead of setting up the loop. The overhead in C is even less, and if using a clever optimizing compiler, there might be no overhead at all.

Summary

At first glance, this idiom looks like an unnecessary trick. Upon more careful consideration, it makes the application easier to understand and maintain. I would use it with compiled languages, especially with an optimizing compiler. I would also use it in interpreted languages, except in a performance-critical hotspot. Even there, I would use it initially and revert to if, elif, elif, elif … else only after full application debugging.



Previous Article
Next Article

Similar Reads

How to use if, else &amp; elif in Python Lambda Functions
Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else &amp; elif in Lambda Functions. Using if-else in lambda function The lambda function will return a value for every valida
2 min read
Python3 - if , if..else, Nested if, if-elif statements
There are situations in real life when we need to do some specific task and based on some specific conditions, we decide what we should do next. Similarly, there comes a situation in programming where a specific task is to be performed if a specific condition is True. In such cases, conditional statements can be used. The following are the conditio
5 min read
C if else if ladder
if else if ladder in C programming is used to test a series of conditions sequentially. Furthermore, if a condition is tested only when all previous if conditions in the if-else ladder are false. If any of the conditional expressions evaluate to be true, the appropriate code block will be executed, and the entire if-else ladder will be terminated.
3 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Python dictionary (Avoiding Mistakes)
What is dict in python ? Python dictionary is similar to hash table in languages like C++. Dictionary are used to create a key value pair in python. In place of key there can be used String Number and Tuple etc. In place of values there can be anything. Python Dictionary is represented by curly braces. An empty dictionary is represented by {}. In P
4 min read
Python | Avoiding class data shared among the instances
Class attributes belong to the class itself and they will be shared by all the instances and hence contains same value of each instance. Such attributes are defined in the class body parts usually at the top, for legibility. Suppose we have the following code snippet : C/C++ Code # Python code to demonstrate # the working of the sharing # of data v
2 min read
Python | Avoiding quotes while printing strings
We often come across small issues that turn out to be big. While coding, the small tasks become sometimes tedious when not handled well. One of those tasks is output formatting in which we require to omit the quotes while printing any list elements using Python. Example Input : ['Geeks', 'For', 'Geeks'] Output : Geeks For GeeksAvoiding Quotes While
4 min read
Maximum index a pointer can reach in N steps by avoiding a given index B
Given two integers N and B, the task is to print the maximum index a pointer, starting from 0th index can reach in an array of natural numbers(i.e., 0, 1, 2, 3, 4, 5...), say arr[], in N steps without placing itself at index B at any point. In each step, the pointer can move from the Current Index to a Jumping Index or can remain at the Current Ind
15 min read
Snake and Ladder Game in C
Snake and Ladder game is a traditional game that involves two or more players and the winner is the guy who reaches the final square on the game board at the earliest. Components of the GameA square board with a series of numbered squares arranged in m x m grid.A dice to be rolled usually uses a six-faced die.Each player uses different color tokens
5 min read
Ladder Graph Using Networkx Module in Python
In this article, we are going to see the ladder graph using Python. It is a graph that looks like ladders used commonly with every node attached to two other nodes in a specific manner. We can obtain a ladder graph by joining two-path graphs of n nodes each by each node connected with a corresponding node in another path graph. Representation: Belo
2 min read
Practice Tags :