Spaghetti Code - Examples

Examples

Below is what would be considered a trivial example of spaghetti code in BASIC. The program prints the numbers 1 to 10 to the screen along with their square. Notice that indentation is not used to differentiate the various actions performed by the code, and that the program's GOTO statements create a reliance on line numbers. Also observe the unpredictable way the flow of execution jumps from one area to another. Real-world occurrences of spaghetti code are more complex and can add greatly to a program's maintenance costs.

10 i = 0 20 i = i + 1 30 PRINT i; " squared = "; i * i 40 IF i >= 10 THEN GOTO 60 50 GOTO 20 60 PRINT "Program Completed." 70 END

Here is the same code written in a structured programming style:

10 FOR i = 1 TO 10 20 PRINT i; " squared = "; i * i 30 NEXT i 40 PRINT "Program Completed." 50 END

The program jumps from one area to another but this jumping is predictable and formal. This is because using for loops and functions are standard ways of providing flow control whereas the goto statement encourages arbitrary flow control. Though this example is small, real world programs are composed of many lines of code and are difficult to maintain when written in a spaghetti code fashion.

Another example: DIRTY:

rubbish = {} i = 0 i = i + 1 rubbish = {=1}i = i + 1 rubbish = {=2}i = i + 1 rubbish = {=3}i = i + 1 rubbish = {=4}i = i + 1 rubbish = {=5}i = i + 1 function PRINTRUBBISHDATAFORANONYMOUSREASONS(i) print(rubbish) end PRINTRUBBISHDATAFORANONYMOUSREASONS(1) PRINTRUBBISHDATAFORANONYMOUSREASONS(2) PRINTRUBBISHDATAFORANONYMOUSREASONS(3) PRINTRUBBISHDATAFORANONYMOUSREASONS(4) PRINTRUBBISHDATAFORANONYMOUSREASONS(5)

CLEAN:

local rubbish = {} for i=1, 5 do rubbish = {} rubbish = i end function printRubbish for i,v in ipairs(rubbish) do print(v) end end printRubbish

Read more about this topic:  Spaghetti Code

Famous quotes containing the word examples:

    In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.
    Michel de Montaigne (1533–1592)

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)