batch-file Best Practices Spaghetti Code

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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

: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.

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.

: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.



Got any batch-file Question?