Microsoft Office Tutorials and References
In Depth Information
2.2.3 Modularity
2.2.3 Modularity
Another major issue that relates to readability is that of modular programming . In the early days
of PC programming (in BASIC), most programs were written as a single code unit, sometimes
with many hundreds or even thousands of lines of code. It is not easy to follow such a program,
especially six months after it was written. Also, these programs tended to contain the same code
segments over and over, which is a waste of time and space.
The following BASIC example will illustrate the point. Line numbers have been added for
reference. (Don't worry too much about following each line of code. You can still follow the
discussion in any case.)
10 ' Program to reverse the letters in your name
20 ' Do first name
30 INPUT "Enter your first name: ", name$
40 reverse$ = ""
50 FOR i = LEN(name$) TO 1 STEP -1
60 reverse$ = reverse$ + MID$(name$, i, 1)
70 NEXT i
80 PRINT "First name reversed: " + reverse$
90 ' Do middle name
100 INPUT "Enter your middle name: ", name$
110 reverse$ = ""
120 FOR i = LEN(name$) TO 1 STEP -1
130 reverse$ = reverse$ + MID$(name$, i, 1)
140 NEXT i
150 PRINT "Middle name reversed: " + reverse$
160 ' Do last name
170 INPUT "Enter your last name: ", name$
180 reverse$ = ""
190 FOR i = LEN(name$) TO 1 STEP -1
200 reverse$ = reverse$ + MID$(name$, i, 1)
210 NEXT i
220 PRINT "Last name reversed: " + reverse$
Now, observe that lines 40-70, 110-140, and 180-210 (in bold) are identical. This is a waste of
space. A better approach would be to separate the code that does the reversing of a string name
into a separate code module and call upon that module thrice, as in the following example:
' Program to reverse your name
DECLARE FUNCTION Reverse$ (name$)
' Do first name
INPUT "Enter your first name: ", name$
PRINT "First name reversed: " + Reverse$(name$)
' Do middle name
INPUT "Enter your middle name: ", name$
PRINT "Middle name reversed: " + Reverse$(name$)
' Do last name
INPUT "Enter your last name: ", name$
PRINT "Last name reversed: " + Reverse$(name$)
The separate code module to reverse a string is:
Search JabSto ::




Custom Search