Spaghetti code means a code snippet that uses many, and often confusing structures. Such as
GOTOs, exceptions and inconsistent code.
Examples and Solutions
@echo off set /a counter=0 :Loop set /a counter=%counter% + 1 echo %counter% if %counter% equ 10 goto :exit goto :Loop :exit
This program comes with plenty of jumps, making us harder to know what exactly the script is doing.
@echo off for /l %%G in (0,1,10) echo %%G
GOTOs, we reduced the amount of code greatly, and we can focus on the actual code.
Consider the following statements.
:endGame if %player1Score% gtr %player2Score% goto :player1wins if %player1Score% lss %player2Score% goto :player2wins goto :tie :player1wins echo player 1 wins goto :eof :player2wins echo player 2 wins goto :eof :tie echo tie goto :eof
This snippet requires lots of
goto statements and can be confusing to debug. To simplify these statements, we can use
call command. Here is the above script at a better condition.
:endGame if %player1Score% gtr %player2Score% call :message player 1 wins if %player1Score% lss %player2Score% call :message player 2 wins if %player1Score% equ %player2Score% call :message tie goto :eof :message echo %* goto :eof
Both scripts output the exact same result, but the new script is much shorter and clearer.