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:
“It is hardly to be believed how spiritual reflections when mixed with a little physics can hold peoples attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.”
—G.C. (Georg Christoph)
“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 (15331592)
“No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.”
—André Breton (18961966)