======================== Less Code is Better Code - stop cutting and pasting identical code ======================== -IAN! idallen@idallen.ca The ability to cut-and-paste code easily has produced a whole generation of programmers who write too much code. You must minimize the amount of code you write, to minimize the effort needed to maintain the code. If you duplicate code, you more than duplicate the amount of effort needed to maintain it. Here are some examples of "too much code". -------------------------------------------------------------------------- You want to use a temporary file name containing the user name $USER and the current process ID $$. WRONG WAY: grep foo /etc/passwd >"/tmp/$USER.$$.txt" grep bar /etc/passwd >>"/tmp/$USER.$$.txt" diff /etc/passwd "/tmp/$USER.$$.txt" rm "/tmp/$USER.$$.txt" - changing the file name requires changing four lines of code! - you have three chances to spell the name wrong RIGHT WAY: tmpfile="/tmp/$USER.$$.txt" grep foo /etc/passwd >"$tmpfile" grep bar /etc/passwd >>"$tmpfile" diff /etc/passwd "$tmpfile" rm "$tmpfile" - the file name is set in one place - changing it is easy - spelling the name wrong in some of the commands is impossible -------------------------------------------------------------------------- You want to process an input file using the above commands. The file might come from a command line argument or by prompting and reading. WRONG WAY: if [ "$#" -ge 1 ]; then tmpfile="/tmp/$USER.$$.txt" grep foo "$1" >"$tmpfile" grep bar "$1" >>"$tmpfile" diff "$1" "$tmpfile" rm "$tmpfile" else echo 1>&2 "Enter a file name:" read filename || exit $? tmpfile="/tmp/$USER.$$.txt" grep foo "$filename" >"$tmpfile" grep bar "$filename" >>"$tmpfile" diff "$filename" "$tmpfile" rm "$tmpfile" fi - you have written the entire algorithm twice over, once for the command line argument case and once for the prompted input case - changing the algorithm requires changing the code in two places RIGHT WAY: - separate the gathering of input from the processing step: if [ "$#" -ge 1 ]; then filename="$1" else echo 1>&2 "Enter a file name:" read filename || exit $? fi tmpfile="/tmp/$USER.$$.txt" grep foo "$filename" >"$tmpfile" grep bar "$filename" >>"$tmpfile" diff "$filename" "$tmpfile" rm "$tmpfile" - the duplicated code has been removed - the algorithm is implemented in only one place, not two - the obtaining of the file name is now separate from the algorithm - the algorithm is generalized and parametrized to work no matter how you might obtain a file name Don't duplicate code. Parametrize the code and set the parameters using conditional logic ahead of the code. Use functions, if your programming language allows them. Less code is better code!