Rarely used loops
WHILE and DO-WHILE Loops
Most programming languages provide options for looping conditions i.e. running set-of code till a given condition is true. We have FOR, WHILE and DO-WHILE loops. But we mostly use the FOR loop for most of the use cases. WHILE and DO-WHILE loops are left out. Are we really using a work around of misusing FOR loop for everything ? Are there any use cases wherein we could fit in WHILE and DO-WHILE loops ?
The differentiating factors of these loops are mentioned below. Let's check them once :
FOR LOOP : It is used for known number of iterations. It consists of a initialisation, increment and condition.
WHILE LOOP : It is used when we want to run a given code till the condition is true
DO WHILE LOOP : It is similar to WHILE LOOP but small differentiator is that this LOOP will run at-least once.
We know these basics but the question is :- when do we really use a WHILE or DO-WHILE loop ? We mostly use a FOR LOOP. Probably we are dealing with data mapping and conditional processing. You fetched some records from backed and want to map it to DTO then a simple for loop is good.
WHILE LOOP use cases
Finding an element in a collection : Using a looping logic which executes till we find an element in the given collection. Although we can use a FOR LOOP and break it if matching element is found but using a WHILE LOOP is more cleaner approach. The conditional logic in this case is to check if the element is located. You may use a boolean flag if needed.
DO-WHILE LOOP use cases
Retry mechanism : When we want to apply the retry mechanism its cleaner approach to use DO-WHILE LOOP because it executes at-least once. Hence if the first attempt is successful then looping is not required. However if the first attempt fails then we can retry till either the execution is successful or if the retry attempts limit is exhausted.
The WHILE and DO-WHILE LOOPS are useful in these and more such use cases but we generally use FOR LOOP with some workarounds which makes code difficult to read and understand. Software code is to be maintained and upgraded for years hence improving code readability is important. Keep reading your same LOOPING code again and again to find if the correct LOOP is used for the logic you want to implement. Remember basics of the different LOOPs provided in a programming language.