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.
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 ENDThe 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 printRubbishRead more about this topic: Spaghetti Code
Famous quotes containing the word examples:
“There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.”
—Bernard Mandeville (16701733)
“No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.”
—André Breton (18961966)
“Histories are more full of examples of the fidelity of dogs than of friends.”
—Alexander Pope (16881744)