Programming languages allow us to be lazy and DBN is no exception. The basic idea to reduce the size of the program from the previous post is to abstract the algorithm’s steps into a new DBN command. The name of the command will reflect what the algorithm produces. The way to do it in DBN is as follows:
command NewCommand V1 V2 ...
{
// algorithm's steps
}
states that NewCommand is an algorithm that requires the concepts V1, etc. to execute the steps that are within the braces. Each concept is a variable that will be used by the algorithm’s steps.
After defining the algorithm, it can be used as a new DBN command, by simply writing NewCommand E1 E2 ... The value of each expression will be computed and assigned to the corresponding variable, and the algorithm will be executed. If more or less expressions are given than needed by the algorithm, an error message will be issued. For example, the same error will occur if we provide more or less than four expressions for the line command. Rewriting our program to abstract the execution steps into a named command should make clear how commands are defined and used in DBN.
// the tunnel
// version 3, 9 Nov 2008, Michel Wermelinger
// define a command for drawing centred squares
command centred_square left
// draw a centred square, given the left coordinate
{
set bottom left
set centre 50
set distance (centre - left)
set right (centre + distance)
set top right
line left bottom right bottom
line right bottom right top
line right top left top
line left top left bottom
}
line 0 0 100 100 // left bottom corner to right top corner
line 0 100 100 0 // left top corner to right bottom corner
centred_square 20 // near square
centred_square 40 // far square
Note that the algorithm’s steps have been indented to show they are within a command. The DBN programming environment provides a button to automatically layout the whole program.
Note also how the program has become succinct while remaining clear. The algorithm’s steps have been written once and used twice. As a simple exercise, try to further reduce the length of the program by simplifying the computation of the right variable. (Hint: Substitute the variables in the expression by their values and thereby get rid of the assignments that compute centre and distance.)
Splitting the program’s steps into several commands (also called procedures or sub-programs in other languages) is one way of breaking a long program into simpler to understand modules. In the next post we take modularisation one step further.