Spaghetti code is a term that’s hardly used anymore. It basically meant that if the flow of your program was all over the place (and not very structured) then it looked like a pile of spaghetti. Imagine trying to fish one piece of spaghetti out of the pile, and you have an idea of what it was like to trace code.
The biggest culprit in spaghetti code was the command GOTO. GOTO meant exactly what it sounds like. Go To whatever point I’m telling you. If you realized at some point in the program that you needed to get a piece of information, GOTO the point where you get that information. Need to print something again? GOTO the line where you printed it. And on and on and on…
Structured programming is the concept of a single flow throughout the program. Every stage in the code (or every block of code in the case of loops and decisions) has one entry point, and one exit point. Sometimes, it may not look like this is true, but if you follow the flow, you’ll see the structure.
Take an If-then statement for example. You enter the if- then statement from the top. If the condition is true, then you follow that path, and if the condition is false, you follow that path. Either way, both conditions will lead to the exact same place in your code (the one exit).
An example of spaghetti and structure lies in this for loop:
First Spaghetti code (note the GOTO which breaks you out of the FOR loop)
10 FOR I = 1 to 5
20 IF somevalue = true THEN
30 GOTO 50
40 NEXT I
50 PRINT “I’m out of the for loop now.”
Note how if the condition is true, you jump out of the FOR loop and it doesn’t end gracefully. However if the statement is false, I is incremented and the FOR loop ends normally. This means there are two exits from the loop.
FOR I = 1 to 5
IF somevalue = true THEN
I = 6
If the condition is true, then you set I to a point where it will gracefully exit the FOR loop. Otherwise, the “ENDFOR” statement will increment I to the next number. One entry, one exit. Either way, you will always see the ENDFOR, and you will always check to see if you should leave.
As you’re creating your flowcharts, pseudocode, or even writing your code, you should take the time to try and “dry run” through the program. See if you can follow the flow and logic. If you can’t, then it’s probably not as structured as you want. Better yet, see if someone else can follow the flow and logic (since you may be able to understand your logic better than they can). Also check to make sure that every block of code has one entry and one exit.
Your goal is to make the program as efficient and structured as possible. This reduces the amount of memory needed, amount of processing needed, and the amount of headaches that someone will have in the future when they have to maintain the code.
With this, I will venture on to pseudocode.
Have a great day:)