Spaghetti code means a code snippet that uses many, and often confusing structures. Such as GOTOs, exceptions and inconsistent code.

Examples and Solutions

Example A

@echo off
set /a counter=0

set /a counter=%counter% + 1
echo %counter%

if %counter% equ 10 goto :exit
goto :Loop


This program comes with plenty of jumps, making us harder to know what exactly the script is doing.

Solution A

@echo off
for /l %%G in (0,1,10) echo %%G

Using less GOTOs, we reduced the amount of code greatly, and we can focus on the actual code.

Example B

Consider the following statements.

if %player1Score% gtr %player2Score% goto :player1wins
if %player1Score% lss %player2Score% goto :player2wins
goto :tie

echo player 1 wins
goto :eof

echo player 2 wins
goto :eof

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.

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

echo %*
goto :eof

Both scripts output the exact same result, but the new script is much shorter and clearer.