ExamplesBelow is an example of 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 needed and that the program's 10 i = 0 20 i = i + 1 30 PRINT i; " squared = "; i * i 40 IF i < 10 THEN GOTO 20 50 PRINT "Program Completed." 60 END Here is the same code written in a structured programming style: FOR i = 1 TO 10 PRINT i; " squared = "; i * i NEXT i PRINT "Program Completed." 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. Assembly and script languagesWhen using the many forms of assembly language (and also the underlying machine code) the danger of writing spaghetti code is especially great. This is because they are low-level programming languages where equivalents for structured control flow statements such as for loops and while loops seldom exist. Many scripting languages have the same deficiencies: this applies to the batch scripting language of DOS and DCL on VMS. Nonetheless, adopting the same discipline as in structured programming can greatly improve the readability and maintainability of such code. This may take the form of conventions limiting the use of Programs written in higher-level languages with high-level constructs such as for loops (as in the second example above) are often compiled into assembly or machine code. When this process occurs, the high-level constructs are translated into low-level "spaghetti code" which may resemble the first example above in terms of control flow. But because compilers must be faithful to high-level constructs in the source code, the problems that plague relatively unstructured languages like BASIC do not haunt higher-level languages. It does, however, mean that debugging even mildly optimized code with a source-level debugger can be surprisingly confusing. See also
ReferencesThis article was originally based on material from the Free On-line Dictionary of Computing, which is licensed under the GFDL.
External links
| |