Structured Programming


Structured programming is the antidote to unstructured programming.  What is "unstructured programming"?

Unstructured programming provides no restrictions on the flow of control in the logic of an algorithm. A "goto" statement (or "unconditional branch") may be used anywhere to alter the sequence of execution flow, resulting in "spaghetti code" that is very difficult to read or maintain.

cartoon

E. Dijkstra first argued the drawbacks of unstructured programming ("Goto Statement Considered Harmful", March 1968 "Communications of the ACM").   A subsequent proof by Bohm and Jacopini demonstrated that any program logic can be represented by as few as three types of structures: (1) SEQUENCE  , (2) IF - THEN - ELSE , (3) WHILE - DO .  

IF-THEN-ELSE
WHILE-DO
if else
while



A structured program algorithm can always be read from top to bottom, sequentially, without arbitrary jumps from point to point.  A key feature is that the algorithm is composed of structured blocks of code that are entered only at the top and exited only at the bottom.  This constraint has two powerful benefits:

Most modern programming languages don't even contain a "goto" statement, but some still contain the break statement that violates the "exit only at the bottom" rule.   Sloppy programmers often use a return statement in the middle of a loop to prematurely exit a loop.   These practices are strongly discouraged. They are usually indicative of incomplete understanding of the logic and a more elegant and concise solution is often available.

This typical poor solution exits the loop in the middle:
        for (int index = 0; index < theArray.length; index++)
        { 
            if (theArray[index].equals(target))
            {
                return index;
            }
        }
bad

       
 The better solution puts all the possible ways the loop can terminate into the loop condition:
        int index = 0;
        while (index < theArray.length && !theArray[index].equals(target))
        { 
            index++;
        }
        return index;
good


With the advent of exception handling mechanisms ("try-catch" in Java), there are very few situations where exiting from the middle of a loop is appropriate.  If a careful analysis concludes that violating the principles of structured programming is the expedient approach, it should be documented thoroughly.

See what xkcd thinks about "goto."