Sunday 27 April 2008

Batch Programming Tip #03: Using The Boring Black Hole

Batch scripts can quickly end up looking like spaghetti code. In my opinion this is mostly because you commonly use the (Really, Really Nasty) "goto" instruction.

There are a few things you can do to avoid "I-wrote-this-program-but-cannot-for-the-life-of-me-remember-how-or-even-whether-it-works" syndrome:
  • Always use the same program structure: init_system (setlocal calls, set system variables, etc.), init_vars (read program arguments and initalize variables), function routines and subroutines, eof (where you go to end and pause the program in interactive mode), blackhole (where you go when you want nothing more to happen).
  • Comment code profusely when needed as things like missing argument, undeclared variable, etc. will not be considered like compile-time or even runtime errors. So you're stuck with you ... and you to work out what's going on when things start going wrong.
  • Although this may not be considered best practice, using intermediary variables can make your code much more easy to read.
  • When calling a subroutine, pass variables as arguments where possible i.e. don't rely on caller program to prepare variables for the sub-routine (something similar to using "globals"), rather pass the variables as arguments (rather like passing arguments to a function instead of relying on global variables). This just makes the script more obvious and easy to understand, as with most programming languages.

So, here's a basic example that simply does... well nothing:



@echo off

:init_system
goto init_vars

:init_vars
SET text=I am doing something...
SET end_text=This is eof...
SET press_key=Press a key to continue...
goto do_something

:do_something
call :pause_prog "%text%"
goto eof


:: this takes one argument
:: @param 1 - the text to show
:pause_prog
cls
echo Message: %~1
echo %press_key%
pause > NUL
goto blackhole

:eof
call :pause_prog "%end_text%"
goto blackhole

:blackhole


Any reusable code is stored in a subroutine (e.g. pause_prog) which ends swallowed in the black hole which is where the subroutine stops and the code then returns to the line which immediately follows the call to the subroutine. Hence the name... but we'll get back to those in a later post. Until then... tchuss.

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory