PutLine ıData(J)); end loop; end WriteFile;. You can see from the above discussion that Figure 1 is the decision chain followed to derive this program using ...
f wSare
Productivity Cons
mm
AD-A286 834)
Software Engineering Using Ada Course: Lectures and Exercises ELECTE SAU(J~195
k* pdb Ammnd ~t
L..
V&sin 01.00 .0 'Virginia
CENTER 0 far &frWare ReuSe and Technology Tlrntvd-
isaaI
REPORT DOCUMENTATION PAGE
FormApproved
OMB No. 0704-0188
Pubilo reporting burden forthia oollg=tlot of InformationIs eallmed o average 1 hour per response, Including the ti'ne Ic rev edng instruction*, searohing existing data sources, gathering and nmintaining the data noded., and oorrnlsting aendreviewing the coleltion of Inforrnmtion. Send ,nornmentregarding this burden estimate or any other aspectof thin colaction of Ifornstion, Including suggestow lor reducing thi burden to WasnIngton Heedquarters Servioes, Dkbeotorte for Information Operations and Reports, 1215 Jeffwrson Davis Highway, Suite 1204, Arlington, VA 22202-43M2, and to the Office of Managerment and Budget, Paperwork Reduction Pro eot(0704-0188), Washington, DC 20603.
1. AGENCY USE ONLY (Leave blank)
2, REFORT DATE
, F OORT'YPEANDDATESOOVER
April 1995
Technical Report - Final
4. Tfl.E AND SUB1TllE
5. FUNDING NUMBERS
Software Engineering Using Ada Course: Lectures and Exercises R. Christopher, L. Finneran, S. Wartlik Produced by Software Productivity Consortium under contract to Virginia Center of Excellence
G MDA972-92-J-1018
7. PEFWORMIIG OFRANIATION NAMES(S) AND ADURESS(ES)
8. PERFORMING ORGANIZATION
Virginia Center of Excellence SPC Building 2214 Rock Hill Road Herndon, VA 22070
SPC-94094-CMC, Version 01.00.05
9. SPNSORIG / MNITORING AGENCY NAME(S) AND ADDFESS(ES)
10. SPONSORING I MONITORING
6. AUTHOR(S)
REPORTNUMvER
AGENCY R•=IORT NUMBER
ARPA/SISTO
Suite 400 801 N. Randolph Street Arlington, VA 22203 11. SUPPLEMENTARY NOTES
N/A 12a. DISTRIBUT1ON /AVAILABIUTY STATEMENT
12b. DISTRIBUTION CODE
APPMo~d Im pubA.
I
No Restrictions
1
13. ABSTRACT (Maximum 200 womrs)
This is a short course that introduces novice programmers to software engineering concepts and illustrates them using the Ada programming language. The course, which takes about two weeks to teach, is aimed at advanced placement computer science high school classes. It stresses problems that arise in programming in the large, particularly those caused by change, communication, and complexity. It shows how software engineers employ abstraction, information hiding, and software reuse to deal with these problems. The solutions shown are expressed in Ada. The students see and appreciate how Ada can help them solve real problems. The course material contains viewgraphs instructors can use as the basis of lectures. Each viewgraph has accompanying notes that show how to present the viewgraph and suggest topics for discussion. The course is divided into four units; following each unit are summaries, suggested group activities, and homework assignments. A comprehensive examination and an evaluation form are also included. 14. SBUJCTTEFRMS
15. NU'MBER OF PAGES
Software engineering, software reuse, course, Ada, information hiding, abstraction 17. SECURITY CLASSIFICATION
OF REPORT Unclassified
NSN 7G40-01-280-5500
18. SECURITY CLASSIFICATION
19. SECURITY CLASSIFICATION
OF THISPAG Unclassified
OF ABSTRACT Unclassified
162 CODE PRC CO. 20. UMITATION OF ABSTRACT
UL Standard Form 298 (Rev. 2-89) Prescribed by ANSI Sid. 230-18 298-102
Software Engineering Using Ada Course: Lectures and Exercises SPC-94094-CMC Version 01.00.05 April 1995
(0 Produced by the SOFTWARE PRODUCTIVITY CONSORTIUM SERVICES CORPORATION under contract to the VIRGINIA CENTER OF EXCELLENCE FOR SOFTWARE REUSE AND TECHNOLOGY TRANSFER
-
SPC Building 2214 Rock Hill Road Hemdon, Virginia 22070
,
Copyright 0 1995, Software Productivity Consortium Services Corporation, Herndon, Virginia. Permission to use, copy, modify, and distribute this material for any purpose and without fee is hereby granted consistent with 48 CFR 227 and 252, and provided that the above copyright notice appears in all copies and that both this copyright notice and this penpssion notice appear in supporting documentation. This material is based in part upon work sponsored by the Advanced Research Projects Agency under Grant #MDA972-92-J-1018. The content does not t. w.ssarily reflect the position or the policy of the U. S. Government, and no official endorsement should be inferred The name Software Productivity Consortium shall not be used in advertising or publicity pertaining to this material or otherwise without the prior written permission of Software Productivity Consortium, Inc. SOFTWARE PRODUCTIVWTY CONSORTIUM, INC. AND SOFTWARE PRODUCTIVriY CONSORTIUM SERVICES CORPORATION MAKE NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABIUTY OF THIS MATERIAL FOR ANY PURPOSEOR ABOUTANY OTHER MATI'ER, AND THIS MATERIAL IS PROVIDED WITHO/FT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
IBM is a registered trademark of International Business Machines Corporation. Macintosh is a registered trademark of Apple Computer, Inc.a Microsoft and MS-DOS are registered trademarks of Microsoft Corporation. Windows and Windows 95 are trademarks of Microsoft Corporation.
CONTENTS
*
Tab Unit 1: Software Engineering .....................
1
Unit 1: Software Engineering, Workbook ..........
2
Unit 2: Abstraction ............................
3
Unit 2: Abstraction, Workbook ................
4
Unit 3: Information Hiding ......................
5
Unit 3: Information Hiding, Workbook ............
6
U nit 4: Reuse .................................
7
Unit 4: Reuse, Laboratory .......................
8
I
I
9
..............
Test and Survey .................
9TICIT. t3
. ..............
o
Q
...
iii
Contents
7his page intentionallyleft blank
Iv
0Mw 1ý 01%
X
tK
N. A
~
R
A'4
1,7,
w
w
i
A0
o
,o2"
as
7•
2C.)'
oo
t 0
;:co
> tV
C
=
. 0 aoO0• 2. cc$(5
.
C
C: -C,.
E; 1)
(
.a)
. L_
0. w~
o
-o'
0 C.)
(3)
(30 CL $. o r
0o-
0
.xG)o
0
C"l
C
co
~''
Qc)
.
ooco .-.0 . a-- cr.o (D N CCSC
-0
(3)
CD
o
M~~c~,=U asa--00 cfl&_
E-
Dc
n
U)'V%.
= 1~fO0
C:t
co
•
"o
--
o a
0
W=o
C: >.G5l0
c:0
oI:Cl -
c
01
CD
••
oClVD OE -0 0
co
'"
'••-
o
"E 0 w ~t
0
> fl CC$
-n
0
E
CL
r co =-CU
E
w
. 0,
-- 0
.
3
,C. 0
(3)
3
0) CA '-" •'0 .E 0 1- '-• •,-o
.
,
•
,.-
"•
.-
E
"'
--
g
(DC r
.0.
)
,_ -- a
0
C
q v2 O..0-E 0 E 'o MA a? C
-
CL
_
o
C co' Ca
." 'V
O_ "--
0 C
a)'- %" -O •J -•"0 o 0'4 '
• '' as:
.) CC..
0
Q>%-a O ~CS
E.
U)~C.)C'SCO
C)
C
CD
CO *-a) U)o.
~~U
Co
0
6
0a
E
.-.
H
"
a)a 0~ U)
44) -
V
0i
(U
Cti
Ofl 0.
'-
wi
-
:_
,,
'a
)a
o
0
E
co a) E20 '-e•.,•> ,---o
)
c
0)
..0
-,C I0L.. 0 0
czU ,U*r_
i5
0.O
uE CLE
Z3o
5= Z -.0(
.)o >I_
,o os0
. )
U)C
.- E
- "-
• ED"c(1)
O-.•-
--
~
,,-_0
-o - 4
a
.
°°.
o
coC
-0•-
0--
4)
oo
--
CO CD
.E .-CC -a== )0j. 0 ~
•
0
AO0~ 0 00•, /
E CD -0•_.
o•--D
'a !,--C)=
•=
CU)
00
-"0,
).
MCLa
CO
E
-.
a n ._ oE o-0 ED-
=
0-
_
n I
a
CD '0
-m
O C Ui-.
0l
>
f
v
M~ 0
)C
) 1
co
Cc.
Cd
C
0
c) c o~ z )~ .
0 P G)
0) Loc >~
:3
OW
- 0)
0)
0) m Qr
CU
0
4--CD 0
CD
CDD
'0~
)
0)0
~
(D rC:
0
c 0-
a.) 4-0)
0
C) 0
0)0
1)
-( a~-)
4
Cr
"--.
c
C CL ?-0 (n
n
0z
E
Da 00
0
( 00
-W-
")~
a
)
0)
0 C0
ca-
CU.
4-
.-
-
U)
0
ca~
--
~
~
a)
mOO
I-
0 (D'~ 0 w' mC
E,
2
CO4)Q-0. 0 -,.ItC)
0 (dW ý
) 0 a -~a)O (DC C: 0
Q.
-
(a c
U-~ )
0
c o~
0a >C
-0E-)D o~ ) cis )
E
W:
0
0
03
4--(
t7C -0
00
4)
-X
.5E
) E
(Z
E) Co -0
cU (D~,0
U.. 2
0=
0 CC
4
'-.
co'~
0()
0
00)
Q)
0--
5-
1
CO z)~U2.
-0
20G)>c
0
-o~U m,-E-
&)
~
05
3z-~
o) CT0)i ~~o(UC~
)
0
)
-.
0) 0
C
~m0 W
0
F5 E
0)
C
r
i520 0~ C
)
E3 co
E
9
V,
=
0
U0)
C&=)
V50)
,a
0c
00
-:; 50c ) ccaC ) cD 0)C~D(U
a) M
0
a)~
2, *
0
-
ca-
0)E
CE
"ccc
CDo
0)
C U.
ui
)
E Q)U)
>%rC: r 0
cm.0
CD
10
coý a) _
0Ed
0 7
f
u~
OQ)
= N~U) ECn1
-a
.0w
1-0
a
0
a)
O
0
0
10
C~CD C
Cd
> gcri
E)~0 E Ž.c:
y0
Co 0r
C >0
0
4ý~C3. (D
""a
*-
0rs 0~ a) 0j
ý5
-
.)C
(D
a)-
-
c
0
o
_
0j 0)c0
0
0
~0
'0-
E
Cn( U - -= r-..
0..
0r co (n
0
_:=
~a (0r.
:
CF) c
C)
-.
-.
a)CD.
0
% ~ c~U 4-LCC -Cp0)0 (l-q
0
0 D 03 cn0 ) U)
Q) CL)~9
(
0)
Ca C>
.m
Cx...
D
0
E
D
-"
n
U.) CO CMU C
=C
co=
C:
:a
as E
CflC CDU
~
00) E0) XU)d
C 0ca
0
03 CC*M OCO
X
U)
cC
0d
~cza)
c
U)
0
.
0
-1.o
0
co o)~ CD:C 09
c.
o~
Ir
=~E C: m
w C:cnO
CDO~
o~u
c:
Co
CL.
0'
c)
C-
C
OnHca
EU
00
ow a, tmC
IC
E)
a)U
XM0 m
Cc$
0 L.0.
C
U
0
1
.
... .F....
@0
0rUB1
CL
00GylU3
v:
-0,
( _UQ.
n(1))
-
.8E
2
0
(D
Ez
(
(-
o
0
Eo
L • 0 C-
(nC-.
a_D
C CO
O-0
O~ CD `3
W
0) a)
*0-
c
n
="
CD• CD W
ca
o•o o•=-E ) c c0) in (Dt CD !=
r-
o
C:
>,i"
0
•
"
a)
0o
--
- Dci 0II
0E0)5.-0 E 0~-
(DI
"0
o,.0
0-)Eo0"•
Eo •o
.a
E
r,•• •• CL,
occ =
0
r-
CDp
cc$•.,m o"
=:w~
)E 0
A
,
="
T.. "
3 C:
CL
.c~•o 4-4
C. oo
(nja 0 E o 0- E-o.uo S°- a.o.L-)Z 0 . 0) ) :0 U)0 )D 0, N C0~0 CL~ -%4o1m4
X
-
C-
CC
0° M~()
:(sU
_ r•••• •
-
C: CO °0
,E,._ V (I)CI . =
• c$
cE
o
i.
- a) -t:
Sca,->0
=
"0
0r--.3
Ed3 •~~~
0l
0)
o:,a
• ~ (D•"
•oE
nc0 M
00 0I.
CJ_ ) .--
E
0-
CD
ct$
0 -+
Lm
E
"0, 0" a .
"0
0
_C C'-
as
E
CD
ET do
4 C--
-0 CD"
CD
!-Z
0
CD a) 0QC r -*. CIJ:
-
-
0
a
.
00 "o
0)
NN-
E o6 Eo
.
D
€
:C
0o
CUO
O CU)
C-
o0 "-.-a•
, -,. CD -0 z 7Z . . .CoIH> (D C._
-
:
0-
CI.i-O
2-
a
I-
CC Cu-
CC C>
0
-
I1_. IOm
CL
0o =.i
2 -._
x
E
"
2 ">
E1V (0
S
BE
0 -E
Z,
CI
E E~,
0
00
010
ce) E.J~~0
00)
~
co.
0C
E
co~o.
0 6ýE
U)
00.
0 Eoo .6-W
C r- so
W0 n0) E
0
(j)
X0ýoc
L)
2 aE
0
0
r
L.0
0 5 co c~co
Lo 0)~0
E
a
CL a
a
co
r U-
;r4-;-
0
i2
o0 0h-
c
Uo0
E
E
C
E 0-
Er,
&-
8)
Ex
%r
coc
+.)2
.0
E
00
MwU0o
O
2
E)C
.0
-~
0 co (n
zL
r-
0
cn ()
() 0 -4-
o)
tU)(
4J
-
----
c W
4) .C.
10~ co :3U-
ca z - C 0
CLo0
-WW5
(D 0
0) Ci
=
0a)
C )
a 0
0
a) -
0n0
)
0L 0-0H
U)
E
0)
O
>
ow400.
0D0
COh)O
(Dw
0
IM 0
0j
.Eccn
0
00 Ii
0.
0.0
arm"
spow
0
0 c
• --
o~
co
>,0,
Ow
-)
a)
00-
,,:
(•
ci-s
-0
0, =3
r
0.--
•2) *ý Q m--
E o.---
CC0) OW
0
m
•.•
'•-
0)
46C
0
0
W -
co .0 ) •:3( ,
cm
ZC
:- b.
-
-
- 4 CD 0r_ .
.0
*ýc
L=a
0L
l'I'
,0= .
.L
,-
oo
A
=' 0
c -
a
r-% C 0 0r) w
U
0
•
if
~o a)8l >
(3 - 0
-~
C.
U-aC4-EE _
DC
(D0U )
0
a U
02 coC>0.c
2
,
0)
0
~
'0
2
xC cr- . 1~
0)
o ~L0ECo)E CO1z.U~
)+C.c
CU)d4'
0D~ 04 ~4 E cd D :t m -EE3 "0 U)OVnc D :3=* o )
0U&CU
cm.-
) 2(D
,
.rc 0 E~ o
-0 CD
21 o ~ EZ 005'C/ 0)
-
EU 0
-
ol
0.0 0 0
r CD'r-:3 CM ,
=. I(D 0CC
.0
o
E
00
o&._E..
cm
0
0
.,
L:
(DC00
00
c
a
0'~ v
E c
x0E-®oS.--.-. )0U.%-. c ,
E ooooo
0i
CD
1- (
0)*C.m S- P
0)0
0
0-
c 0 -E. E
.. 0)a+.. > OFa, c:2a(DQ)E1
"-00 0
4
)
a
r- ( ) E oom(nQ" . E 'r0
L0C
0
cC0
(D00-~
1
CLO"
0..
2
or 0
w 0C
-4-
" u) >O
0'
r
V
CD z - CM .. 2C-. C -C W~UE5
o oC
(D
-.
a0 ,' o O
0D
0D
(A
,,_,-
co b_
-, a) •.00.
0
r-0 CC0c
0' ~E,
o,,.D
00
U
(
IL
C
a" E- ca -,- O 0d a)
._ =d o
o* 0
""-a
.9
C
lýa
c )c
z%
cc
0
wL
16.
0)
E
E 0
CD
0
0
(1)
"000
!n
0)m
4--O cm 090)
CO
W.
E
50) CJ OD--
01
Ccr
Ico
'-Co 1 00
d
L
=
0
-
V
$ CO
-::
"D~r-
.
0
a).
o
0z
() = CDC
_6DCL E~f0
C -c
cm
E
Ci
0)r
0
oCU
=
CZO~
:
Cfon~
CZnC: COe 0
0'
z"
C
Z5 ~
0sa>
CD
0
=3
cCoc~ 0c
a
>. V.Cn
0)4 .l
CDr CD "D
4)
0C~
Co
%,-
0 c-o C;0) (1)C
00 E SlO COV
-a
ca.2,cz-
L-~0 =
&0a) C
:316
0
:3
_
0 *CT
-
0
cn.0l)
0r
"O.W .-.
a
C:I
0.-0)
O
-
5cnQ
CD
0 E (Dr
Cu
.- L N
C 0 )
co3
-
.cO
CO oD
OkDa
(0o nz
w
L..h.
4'0
0-
C0) *
i0
_
0
~
CO
cf~)U)
OC
80.
CD
E))C:3)
~cn
2
0)C
0)
a. CD'
L-
I-a0C
'.-c
0co COW
CD
0
cd Cd -
U)L-ý:e CL
7.e-
o =OCc
Eoof 00
0) pc
>..
4-a E~ 0
:2:2
0)
0
oo (D)~5 COC cOs
OH
c,9
U
0
4))
0
U0
CUCC 0)o
E) 0
mi
0
u.
r.
N
(0
0
0N
0Lo
E
E2
E (UO
_
0
0 0~ E0
OwU 0
o
-
0 cc.
0
L- .
am WOO. 0.
0. VG *
0
'a
Software Engineering Using Ada: Software Engineering, workbook
*
UNIT 1: SOFTWARE ENGINEERING UNIT SUMMARY Much industrial software development produces very large software systems, consisting 71 millions of lines of code. Such a system takes years to develop. It's a team effort, not an individual activity. In fact, a software system is typically a joint effort by several companies. Your Computer Science courses have probably concentrated on writing code. To write code requires many skills. These skills include mastering a programming language, using algorithms and data structures, and using a compiler-all fundamental skills you need each time you create a program. Yet despite the need for these skills, they are not the most important ones professional programmers possess. Writing code is the smallest, easiest part of developing software. There are other activities that consume far more time and require much greater skill. Programming in-the-large (that is, developing large software systems) is very hard. Most large software systems are delivered later than planned and contain bugs. Many people even believe this country faces a software crisis because programming in-the-large is so difficult. Why is developing large software systems so hard? Much of the reason stems from two factors: change and complexity. We will study change and complexity in this course.
*
Once software is written, it changes. This is a fact of life. When you write software, you seldom anticipate all the ways it will be used. (Consider that, as of this writing, Microsoft Corporation has produced six versions of DOS, six versions of Word, and three versions of Windows.) Also, you seldom discover all the bugs. New uses and bugs call for chiange. The problem with change is not that it occurs, but that implementing a seemingly simple change often requires huge amounts of work. If you've ever made a change that rippled throughout your program, you understand why. Theni too, think of how much more work you would have if you also needed to change user's manuals, installation guides, and other supporting material that accompanies large software systems. Programs are complex because of the sheer number of details inherent in them. No doubt you realize that the larger your program, the more things you need to keep track of. But really, complexity only truly manifests itself in team settings. Though you may understand your own code well enougrA, you'll experience troubles explaining its inner workings to someone else (you'll have a chance to try in Unit 2). Therefore, when you write software in a team, you spend much of your time communicating with other team members about the software. You also spend much of your time writing technical documents that describe your work. Management briefings, user's manuals, and design reports are examples of such documents. Therefore, complexity necessitates communication. Change and communication make developing software potentially very problematic. For this reason, this course shows software development to be an exercise in engineering. This iswhy Unit 1introduces software engineering as the preferred way to develop software. The dictionaiy defines engineering as the disciplined application of science and mathematics in making systems that are useful to humanity. Software engineering is applying science and mathematics to help you make useful software systems.
*
When you practice software engineering, you follow a software development process, shown in Figure 1.The process breaks software development into a set of coherent steps. In each step, you focus on a particular aspect of developing software:
Software Engineering Using Ada: Software Engineering, Workbook
"* In the Requirements step, you focus on the problem you must solve.
"* In the Design step, you focus on organizing a solution to the problem you defined in the Requirements step. "* In the Code step, you write source code, implementing the plan you created in the Design step. "* In the Test st.ýp, you test the software you created in the Code step to be certain it meets the requirements you defined. Focusing on specific areas in each step helps you deal with change and communication problems. Requireraents Define the Rroblemn. Design Plan how the software will be organized. Code Implement the plan by writing the code,
Utthe software to make sureitors
Figure 1. The Software Development Process
Programming languages can also help you deal with change and communication problems. In this course, you will learn about the programming language Ada. You will see how a software developer, through careful and correct use of Ada's features, can facilitate communication of necessary information to other software developers in a team. You will also see how developers can use these features to lessen the workload in response to change.
2
Software Engineering Using Ada: Software Enieeig Workbook
UNIT 1: SOFTWARE ENGINEERING
*
GROUP ACTIVITY COMM~UNICATION Your Student Government Association has decided to purchase a vending machine and wants you to build it from the following parts: 1.
A money acceptor
2.
A change dispenser
3.
A set of food dispensers
4.
An item selector
Split into groups. Allocate the parts among the people in your group. Working independently, everyone must write down which other parts they think will interact with their own part. When everyone is finished, get together and c nipare your results.
3
Software Engineerirg Using Ada: Software Engineering, Workbook
HOMEWORK Look up the definition of engineering in a dictionary. What does it say? Based on this definition, what do you think software engineering is?
4I
I
Software Engineering Using Ada: Software Engineering, Workbook
UNIT 1: SOFTWARE ENGINEERING
*
TEACHER NOTES FOR EXERCISES GROUP ACTIVITY COMMUNICATION
Your Student Government Association has decided to purchase a vending machine and wants you to build it from the following parts: 1.
A money acceptor
2.
A change dispenser
3.
A set of food dispensers
4.
An item selector
5.
A coin return button
Each of these isvisible to the person operating the machine. Behind the scenes, however, they work together to provide people with vending services.
.
Split into groups. Allocate the parts among the people in your group. Working independently, "eryone must write down which other parts they think will interact with their own part. When everyone is finished, get together and compare your results. Figure2 depicts one possible set of interactions. Item
Food
_
Dispensers
Selector
Money Acceptor
.
Coin Return
-
Change Dispenser
Figure 2. Interaction Among Vending Machine Parts
7hat is, the money acceptorlets the item selectorknow how much money has been fed in to date. The item n, u ,if.JeS ^ste d.dispe.er-wh.en the •person...... 1. choice and arrangesfor changeto be dispensed
sele.,c
if the person hasfed in more money than the item costs. The money acceptoralso notifies the coin return how much has been fed in; if the person presses the coin return button, then the coin returnhas the change dispenserprovide change. ThL is only one possiblesolution. When students do this activity, they willprobablycome up with conflicting ideas of how the parts interact. Of course, if they had agreed or.how each part behaves beforehand,they would not have had this difficulty. This activity illustratesthe need for communicationin software. Too often, group members begin working without a clear idea of what everyone else is doing. The result is akin to what the students will experience in this activity.
Software Engineering Using Ada: Software Engineering, Workbook
HOMEWORK Look up the definition of engineering in a dictionary. What does it say? Based on this definition, what do you think software engineering is? Dictionariesdefine engineeringas the applicationof science and mathematics (some add arts)in orderto make propertiesof matter and nature useful to humanity in structures,machines, systems, orprocesses. Software engineering,then, is the applicationof science, mathematics,and arts (to appreciatethe artistic component, look at some modem multimedia applications) in order to make properties of matter and nature useful to humanity in creatingsofiware systems. There are two types ofproperties: 1.
Propertiesof matterand nature. These come from the problemyou're solving. Forexample, ifyou arewritingaprogramthatcalculatesthe time a balltakes tofall when droppedfrom a certainheight, you use propertiesofgravity as determined by the laws ofphysics.
2.
Propertiesof software. Software is not matter,and it does not occurin nature, so we must consider itspropertiesseparately.Softwarepropertiesinclude algorithmexecution speed (the big 0 notation) and memory use. These propertiesare what make up the discipline of computerscience.
6 6
_
cmJ
U-ci
CLoCO (1)
o 05 L-
0)-
('1.
CD Cd
C06 C'
o im 0)0
0)
O
0
>0D
~
CR
C
Cb
CD
C1
cio SD CD
m
r-
0 )00
E
(DE a) >
:E0~~~
o C
0..
C%. >0
CD
cn
C)
-00 )
t
0
"
~
,
0
EC
-0
_
M
E0
0
L)
-
~
co
CD
(a
0
%
CC
-
@
I
DC ::0
~ 0E ' cnCI; a
c
0
0
D
0
a).
a
a"a C(0 cc0
Lo
o2 (0Owmno0
*~
E
~
0)20 t
O00
0~
ac
*0
CLU
CL
0CL0
cc
0)
to 0 * 0t) o
E
oo-
'0"
-
3>1
(D
=a 0) 0 a •0
0
0Mt:,
c 0
-0
D
*.*:>
=C)~
.2-
"00
00
-
0
..r
,
0
V
"
•
-
0
*k
(
*
0
co
0.
•
) 0u)
E >"u) -'
E-c
2 L0
N 0,(
.-
0
.0) .--
o
S
=0.o
I
(D N 0(U
,, .,o
W,
0) 0
2
m0CL
o
a,
o
0
.W
0
0
0 00
- CL. --
-t03 0•
~~: .. ..: ... E 6
e0)
CU
0
oE
',~C '0.+ cao =j r- LLE a *Ln E~(0
S3-
• ()v
" "
m-z (U . .. .9
c co
-)
CwOwo)VXC) EE
0
_= •)•••"v 0 ~ re CDu •o _m
0 N.
0
CL
E.
2Q,0U
Lc -E E U0
I-d0• o ^, Eoc-111
o
E
-I
,-
oE0 " *-
-
o
(D0-
a ,~
0 -@
...... "--(-U
v
E 50Ž.~
CUE ~~~~
•
0
-
(
S0 cc 'E "--
C
ml.I,,
(IIno
o
C
-
o L.
.UIC Cc
Elm
CL~
CUr
0 nN 0 00 -
"U- ECLU
to
)wM
>(U mI 0
EO
w
.
CL
,,,0'
cn
Ic
co~
C.
a
cis~
0
.0
20 E c
0
'-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(0>..
o a)o
K
-0_
U)) r-
CD
0DU) 0
.
C.) 5,cdC -0
C
C
>
0~
o
>C.
a
0
.0
E
r- -0 Cd
d)C
ja
l- 0)0
co
i 0
0
Cd ci)d
CP% --) )
0
0
0
C o
-0 cz >.
CD (D~~C00
.026cE
aCt
0
0..'
-6
o Qoci o
0
(3 Lc-0 > Ooo
HU)C*flC0fl
0
w
i 0 E
Cl
I
0 2?
(OD
0
C
0
0
,]
Clo t(0
cd
0
0~
,.+ e- . 1CL
0 0na
g0
r-in
C"
0
o) w. CLl __
0
0
-,,= 0
NO-N C"0
I .. ..
_...
C:0
0
00
C,,
0 C-
00 =. > 0 E
E Ec 00.0
C:
-o
CDQt
0)
0
CD
-o
a CZ0 rc~u CrE
0)
cca
0
0z
=CD > 0
8
0
C O
"'.C
)
0 )
EE
CL
(0
na
00
.0
0
Il 150
-0- .0 0)E'
in~
l
U))
Co
cd--
0
-
~
a)0
E.0 Cc
01
C)0
cc cc
E
(0)
1P00
.
El.C
rO
a)
(00
CCr Cc-~cE CJ -W
00
OE.0~
C
Cc
U.
0
Software Engineering Using Ada: Abstraction, Workbook
*UNIT
2: ABSTRACTION UNIT SUMMARY
ABSTRACTION
Abstraction is a technique employed during software design. It lets the developer temporarily suppress irrelevant details so he or she can concentrate on essential information. Developing software requires defining a great deal of detail, so any techniques that can be used to consider information selectively are of great value. Abstraction is one such technique. What is "essential information" and what are "irrelevant details"? Typically, essential information is the data you need in your program and what you will do with it. The irrelevant details are how you will represent that data. In general, you can use this division into what versus how to help you differentiate between essential information and irrelevant details. 'For example, suppose a program is to create a file of integers whose content is that of another file of integers, but in reverse order. You can design a program that does this as follows. The program will read the integers from the input file, storing each one on a stack as it is read. When all integers have been read, the program will pop each integer off the top of the stack and write it to the output file. In this design, you have ,.reated four modules: one to read input, one to write output, one to hold the stack, and one to contrul the others (see Figure 1). input Module
-
Cntrol Module
Output Module
7
6 Stack Module
5 4
3 2
1
Figure 1. Module Design for Reversing a File of Integers When you're working in a team, it's important to create the module design. You can assign each person one or more modules. This is a good way for team members to work together.
*
Recall that a stack is a linear list of values accessible only through a fixed set of operations: Push, Pop, Top, Is Empty, and Size. This statement of a stack is an abstraction. It proclaims the essential information-namely, what five operations can be used to access a stack. It also defines what kind of descriptive information other packages can see, for example, the stack's size. It suppresses irrelevant details, such as how the stack will be represented.
Software Engineering Using Ada: Abstraction, Workbook
This essential information is the abstraction's specification. In Ada, you can package the essential information to show its interrelatedness.* package IntegerStack is procedure Push(Element: in Integer); procedure Pop; function Is_Empty return Boolean; function Top return Integer; function Size return Integer; end IntegerStack;
In Ada, the package construct groups together a set of procedures and functions. (You can also include constants, variables, and data types, as will be shown later.) Everything between the first line and the end line is declared to be part of the package specification. This package specification declares two procedures and three functions. The first procedure, Push, has a single parameter, Element. This parameter is declared in, which means that you must supply a value for it when you invoke it. Furthermore, its value will be unchanged when Push finishes. The specification gives you enough essential information to let you write most of the program.** with Integer-Stack; pxocedure Read-Input is Element: Integer; begin Open(InputFile, In_File, FilePName); Set-Input (Input-File); while aot EndOfFile loop Get(Element); IntegerStack. Push (Element); end loop; Close(InputFile); end ReadInput;
with IntegerStack; procedure WriteOutput is Element: Integer; begin Open(Output_.File, Out_File, File_Name); SetOutput (OutputFile); while IntegerStack.Size > 0 loop Element := IntegerStack.Top; Put (Element); Integer_Stack. Pop; end loop; Close (Output_.File); end Write_Output;
These two procedures both begin with the line with IntegerStack, meaning that the information in the package specification of IntegerStack is within their scope. They can, therefore, within invoke Push, Pop, Top, and Size. Notice that references to these procedures and functions are preceded by the package's name and a period; e.g., Integer-Stack. Pop. This is Ada's way to avoid
ambiguities, since other packages might have procedures and functions with the same names as those found in Integer-Stack.
The package specification serves aq a contract with other modules in the program. When you write it, you are suppressing the implementation as an irrelevant detail but promising that you will develop an implementation that provides the functions stated in the specification. In Ada, you place this implemeatation in a package body, which is separate from the package specification. *
In the code fragments, Ada reserved words are shown in boldface type. For simplicity and clarity, the code examples omit details of file input and output.
2
4
Softwari Engineering Using Ada: Abstraction, Workbook
package body Integer-Stack in Index: Integer := 1; type Stack-Representation is Stack: Stack_Representation;
procedure Push(Elexm, Lt: in
array (1..100) of Integer;
Integer) is
begin Stack(Indox) := Element; Index := Index + 1; end Push; procedure Pop is begin Index ;x Index - 1; end Pop;
function Top return Integer is begin return Stack_Contents(Index-1); end Top; function Size return Integer ios begin return Index-I; end Size; end Integer-Stack;
Other modules, such as Read-Input and write-output, do not need to know any details of the implementation. They only need the information in the specification. The Ada programming language enforces this. Read_Input and Write_output can access the information in the package specification, but cannot access the infonration in the package body. They can invoke Size but cannot determine that Stack is an array or that Size works by accessing the variable index. The designer of IntegerStack has hidden the irrelevant details. This shows how you can use abstraction to write a module that shows to other modules only what you consider to be essential information. Ada packages help teams design and implement programns using abstraction. A team will assign a single developer the responsibility to develop a module such as a stack. The developer will design an Ada package specification for the stack. He or she will then compile the stack's specification and place itin a cenrll-L.PaL y ti-Lat alih Lhle o team memnber' c"-- ancss The other members who need a stack can reference the abstraction as they develop their own programs. This gives them access to exactly enough information to design and implement their own modules. Meanwhile, the stack developer will implement the package body for the stack, then compile the package body and place it in the library. Note that other team members can compile their modules without the stack package body, but they can't execute them until the stack package body has been placed in the libraryl
0
I
__ _
____ ____
__
Software Engineering Using Ada: Abstraction, Workbook
This page intentionallyleft blank
I =
4
Software Engincering Using Ada: Abstraction, Workbook
2: ABSTRACTION
*UNIT
GROUP ACTIVTY Split the class into two-person teams. One member of the team should examine the following code: type A in array () of Integer; procedure p(pl: in A; p2: in Integer; p 3 : out Integer) is u, m, 1: Integer; begin 1 a'lfirst; a'last; u while I < u loop m := (l+u)/2; if p1(m) = p2 then p3 := n; return; elsif pl(m) > p2 then U Mn-1; else 1 M 4- 1; end if; end loop; P3 := a'first-1; end p;
Describe the irrelevant information in this code to your partner. In other words, do not discuss what you believe is the purpose of this code. Instead, discuss only the algorithms and the data it uses. Your partner is to guess the essential information from your description: what purpose the code accomplishes. The essential information should be described in terms of two things: * The value of p3 when the procedure finishes executing 0 The name of the procedure
0 5
Software Engineerinng Using Ada: Abstraction, Workbook
This page intentionally left blank
C
Software Engineering Using Ada: Abstraction, Workbook
UNIT 2: ABSTRACTION
*
TEACHER NOTES FOR GROUP ACTIVITY Split the class into two-person teams. One member of the team should examine the following code: type A is array () of Integer; procedure p(pl: in A; p2: in Integer; p3: out Integer)
is
u, m, 1: Integez; begin 1 : a'first; u : a'last; while 1 < u loop
M := (1+u)/2; if
pl(in)
- p2 then
p3 : = ni; return; olhif pl(m) > p2 then U :M n-1; else
1
:
in + 1;
end if; end loop; p3 :- a'first-1; end p;
Afew words are in orderto the teacher who knows Pascalbut notAda. You may wish to rewritethis example in Pascalfor your students, since the purpose of the activity is to understand the algorithm ratherthan to learnAda, In any case, here is some explanation of the code.
"
The notation < > in the top line is Ada's notation for unconstrained array bounds that are determinedwhen aprocedureis called. Thus, any arrayof integerscanbe passedto p The notations a I firsb and a 'Iast (read "a tic first" and "a tic last,"respectively) are the upper and lower indixes of whatever arrayis passed to a.
"* Instead of.Pascal's while condition do begin statementl;
and
statementn
Ada uses while condition loop statementl;
7
Software Engineering Using Ada: Abstraction, Workbook
statementn;
loop;
end
" Ada's raeturn statement causes control to return immediately from the procedure in which it's executed.
" Insteadof Pascal's it conditionl then begin statementl; ... ; statementn end else if condition2 then begin statementz . staternenta; end alse begin statementA; . ; ztatomentZ end
Ada uses it conditionl then statementl; ... statementn; elsit condition2 then statementa; .. ; statementz; also statementA;
,..;
statementZ;
and if;
Matching each i f with an end if eliminatcs the need for begin blocks. Note also the elsif, which clearly shows that condi ti on2 logically matches condi tioni. Describe the irrelevant information in this code to your partner. In other words, do not discuss what you believe is the purpose of this code. Instead, discuss only the algorithms and the data it uses. Your partner is to guess the essential information from your description: what purpose the code accomplishes. The essential information should be described in terms of two things:
"* The value of p3 when the procedure finishes executing "* The name of the procedure The procedure p is a binary search algorithm. The identifiernames are deliberateiy abbreviated to make the activity more challenging.A better declarationwould be: proetdurc Perform_BinarySearch(Values: in A; Element_To-SearchFor: in Integer; LocationOfElement: out Integer);
This procedure specification succinctly captures that essential information which must be known to developers that use this procedure.However, as they write theirmodules, they do not care about details of the inmplementations like the identifier names.
a
Software Engineering Using Ada: Abstraction, Workbook
.
The student asked to listen to her or his partnershould, in effect, come up with this declaration.In other words, the proceduretakes as input a sorted array of integers (p1) and an integer value (p2). It returns in p3 the index of the value if the value exists in the array.If the value is not in the array,it returns in p3 the integer value that is one less than the first valid index into pl. The student presentingthe irrelevantdetails might say something like: "The procedure has two inputs. One is an arrayof integers. The second is an integer.It declares three integer variables. "It begins by assigning two of the variables the lower and upper bounds of the array. It then checks to see if the second parameterequals the value midway between these two bounds. If it does, then the procedure assignsthe index of the middle value to the thirdparameterand exits. "Ifthe second parameterdoes not equal the value in the middle of the array,the procedureresets the bounds it will check. If the secondparameteris greaterthan the value in the middle of the array,the bounds are reset to the first half of the array.Otherwise, they are reset to the second halfof the array. "This process repeats until a value matching the second parameteris found, or until the difference between the bound is 0 or less. In theformer case, the thirdparameteris set to the index of the matching value. In the lattercase, it is set to one less than the array's lower bound." This activity will be very difficult if students do not know the algorithm. If your students have not learned about binary searching you should substitute an algorithm you have previously taught them.
9
Software Engineering Using Ada: Abstraction, Workbook
This page intentionally left blank
10
'4 I..
:1111 .'
*
U
-
0
C
.1 0)
'S 0) C
.5
0)
C w 4)
w
t o3
C
=)
M)
.-
E
0~
U))
0
0
*0)
a 0flch
0)c
c -:
E
U=VCDCD "&"
c0
U0 Cbn-
a 0)
23
=
as
D0
(D L-U). D)
-0ci)
.-
W
O*CD
-~ :-
o
QC E E0-
W"O ca 0
t 0)0
5) (D 0)~L
0
UO#--st
=
E
0r 00 C
. = O C:c
24o #ý 0
C:
0
CL
*-'
_D
ri r-
t
0
E0
u
CD.0
t
D
C
l
c
0.
Z0Ž~).
0,.
E). *
-
54
6 0
ca ,
( a:00U)
0c$F
CD
2a
0C:0 C 0l a- C5.V ( CD a)W0
*-ci, E0
.)
C) 00
0
0
XU .coO
4-I 0 o
CL
.0
00-c
E2
0
E)
CDE
CD C :3
%-
E
E - %E u C CEU
ý, .c
Vx
O0 (
-
v
Eoo o
= n
(5 =
E
.
'E)_
Co
O
r•
Z
0E 4-1
E an00
.
OD
C.
0
o o o o 10
.. N-~
-~~).-
0~
•
v
C))
~0a
0
--- I--
.
o CZ'
r"
L
.E
•
_
"D
"3 E
0)
•.:
C C
--* *
&.. r-00En E
•
o,, .I "a 0~ a)~C-•tO,ý 0 *r0 EU-. CD"
r-0
-.--
0.o
•J,
a)oo
._-
U) 0-
*.. M,"
C)(nVia
I-.cca)
E)
a),
-0
$-- =,. o• - ,.,b..,= - = 0D _
IC4.=_
--
o-o
0
"
~~0.
Ec
a0ZC
OEa)I-
)
~00')-00
o,0
CD a)•
-,
OR d
-
.
•D
-
C~
EEV'4.o~j
~1
U)
0 0
0.
.
0
4CD
0|
X- -
0 ,- u %->CDE .-. = -_
•-•
Z
.co"
,cE
a 2
£ o )...) o•E_
0C
(
00,
-
C") . ,
o "-
I
()
S
00
UL V
E
o
Z 0
COL l)
a)
-3
E
LE)
SE w~
cz
z
co
.)
a)L.
&"'
0
0
CD
:.
(1)LL
,-G0
17
Ca
_____'c
CD)
WC
0.
-14~
0.c
CL 4 ~0
0
C
_)
0~0
0C0
LL
r)w
-
)-
r
0FE0)0 = CO.)=
co
%.0 l-,
E~a
c'z>
cc$
0~ CD
C:h
0
0
00
'-O _
n
cn C0
OCD 0 0CL
.CL:ýO
U.
1
0
§
i
Ia M c0
)m~
c
CO-
4(J
M.-).0L(O)'
%E
) a.~
.0
)Nr
C
(DQ) M8.
Q
)
00
a)
cz
cLL c
c0
b
W-
=~ 0 " C
U)
k- -oV
E
F
~
*:3
o
)
:3C 0. 0 r-(/
An
CD
:
a)a .O cc$~
.
C:~=
0)
n
E2 c
a))' 0)
a)0 El p
=.
(D E~ ~:00*-0
a), Cl
c~
o~ 0
:;,
C
c$
o
c
dU)o 0
.C~ )(
0
~
~
(1).2J =C(DC
0
U
0)4
E 0
_
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W .
4-.
0)
4-us
0r
czt 0
0
0
-,-nV
0
E
.~0~.
o
n
U_
1-
0
C:
0
C al)aI~'
b' 9
-0VE
E 6~ 2
0
1-2
E
A$.-
%.- a)~a~ Cc~O
~C 0-lal "Clou
W a
l
EE
0
m
0)
00f
*M
0W0OM
E
~
m
LLG
0
CLU
0
E0
C
0
- C•
0
CD-
CD
0~j
2E)"'-
.
",_ E,,,
.I.
cm
) )
.,s ,_.u)s EVI.
;
O
Co
0)
0 U)
00 :: 4CL •-o. E
E a
o0,
--
~
GT
-7
CD 4-
O
.- -s_,
(n
V
(.00
0
S
0
0
V
Cl; o
V~00
-o
(D -- ,e a0
>0 Q)
04-c
-:l
D L•-
'-o o
Coc
or • I
E
0 a , (D~O4-
00
tC
0
*
zCD
0)vcCD 0
~
Eo
om
"
CL t
t
0
-
" '•
0
0 a
0
C
c
- o.:3 '.
cCF 0 N4o
O
*v.. ::...DI Q
.a
E~
.• Ec.> EC:~
aC)0I L- U
0LLCaJW"
C0-0 0o0chC
-
0
:3. 0 :P
.6
E
00a
C-0
E'"•• , -,-
-
0
(D
= -. ; >(~Cl ,- . ....... _.4 0).0.Linl-' in ) :3C1 ~o a (D a,
0 aE
cD a, 0O0
---
L.a-.CD Q+,
-~
0
E
a)0 *•0- o 70 ""
a:- EL.
0U) )-
C$
c
"V.
C-(D__
°0) on
E,
..
0~
.
E
.:
CD
cm
•
w
a)
: ca• ME:a.)_ E
C
CC
"
0
C
C._•..-cW
0
0 E ' a)0_
,..
cECD "C a) Co a•o .ra= ,c.D Ea-
CD
"0)o
i)O
L
~ ,0
0 a
u
_
Co= CLo.
000 LIM-.
(0 0 MR 0 C
co
0 U-6
o
c
0
00
-MO
CZ)
a)
U)
*:C
o& E
0-
E
'a
=0)C
114
0 "4-
40)
(1
-C ooE /
0
c CD
(00
X-. 0)~-
C. 6
0
t30 ýo
(4
.
ED()
'-B
0) a0 C.) 0)lo
Eo
ca
04-
C:
'0
ro a a-)-
0~
o~
CD~) 'I'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0
-0
>
CO.
0"
E0 )
0-r~'
%4Q
(nI)
4-
C)r 0:0
O
r
CO 0
.co
M
cL
a)0A
3,a.
(n~
0
0-0;_c
Z: E
.C
CD
1.
a
QC
.
0 00
I0
C
NNNE
L. 0 Cu
0ME
~0
E o
ob
0 CD MV
OZN0
Q. C
u
00 onc0
c
L.
MONO0-
NO
E~
-
cc
CO) 0I
*
o_
0
-a 0
0
_
E
w
Software Engineering Using Ada: Information Hiding, Workbook
*
UNIT 3: INFORMATION HIDING UNIT SUMMARY The first step of developing software from requirements is to create a design. In design, you break a problem into a set of modules and a structure. The modules, working together in accordance with this structure, form a solution to the problem. Breaking a problem into modules is important for two reasons. First, it helps you deal with the complexity of software because you can grasp the workings of a small module more easily than you can grasp the workings of an entire program. Second, if you are part of a team, it lets you allocate work assignments among the team members. Stepwise refinement is a popular design method. In stepmise refinement, you break up a problem by creating an algorithm to sohle that problem. At first, you keep each of the steps of the algorithm abstract. If you cannot express a step as a single instruction in a programming language, you refine it into another algorithm. You do this for each step and for each step of each algorithm you create. You keep refining until you can express every step as a single computer instruction. At each refinement, you are making a decision. Once you have made the decision, subsequent decisions will depend on that decision. You can think of design as a chain of decisions.
*
As an example, let's consider the problem from Unit 2 of reading, reversing, and writing. In this unit, we shall change the example slightly: "* The program will read and reverse a set of lines, not integers. The reason for this change will become clear in Unit 4. "* A stack is not used to solve the problem. The implementation chosen here more clearly compares and contrasts stepwise refinement and information hiding. You begin stepwise refinement by creating a main module. This module describes an algorithm that will solve the problem and the data structures used in the algorithm. You do not state the algorithm exactly, but rather use procedures and functions to describe large processing steps. For example, the main module for the Reverser program is: procedure Reverse_File is type List_Of_iines is array(l..1000) of String(l..255); Data: ListOfLines; Input_File_Name: constant String : "input.txt"; Output_File_Name: constant String := loutput.txt ; I: Integer; begin ReadFile(InputFileName, Data, I); Reverse_Lines(Data, I); Write_.File (OutputFileName, Data, I); end ReverseFile;
*
This describes a straightforward algorithm: read a file's contents into a variable named Data, reverse the contents of Data, and write Data to another file.
Software Engineering Using Ada: Information Hiding, Workbook
You next decompose each procedure. You might decompose Read.File as follows:* procedure ReadFile(Input.FileName:in String; Data: out List_Of_Lines; I: in out Integer) in F: filetype; Length: Integer; begin Open(F, In-File, Input_File_Name); Set_.Input(F); I := Data'first; while not EndOfFile loop GetLine(Data(I), Length); I := I + 1; end loop; end ReadFile;
In Ada, a procedure may have parameters that are declared in, out, and in out. The Unit 2 Summary described in parameters. An out parameter is one whose value may be set but not accessed. A procedure can both set and access an in out parameter. The notation Data' first is the lower index bound of the array Data. This notation helps you write code that does not need to change if, for some reason, you decide to change the index range of an array. You follow this strategy until no procedure contains any procedures that need to be decomposed. Here are Reverse and WriteFile: procedure ReverseLines (Data: in I: in CopyOfData: ListOfLines;
out ListOf__Lines; integer) is
begin Copy_OfData
:= Data;
.. I-i loop Data(J) := CopyOfData(I-J); end loop; end Reverse-Lines; for
J
in
Data'first
procedure WriteFile(Output_FileName:in String; Data: in ListOf_Lines; I: in Integer) is F: file-type;
begin Create(F, Out-File, OutputFileName); Set-Output(F); for J in Data'first .. I-1 loop PutLine ýData(J));
end loop; end WriteFile;
You can see from the above discussion that Figure 1 is the decision chain followed to derive this program using stepwise refinement. *
2
For simplicity and clarity, the code examples omit details of file input and output.
____
______
______________________________________Software Engincering Using Ada: Information R-iding, Workbook
Algorithm for main module
Representation of Data (array)
Algorithm for reading file
Algorithm for reversing
Algorithm for writing file
Use a while loop
Use a for loop
Use a for loop
Figure 1. Decision Chain for Stepwise Refinement
Stepwise refinement has a hazard. The decisions made early are often crucial ones and, also, are often subject to change. Because decisions made late in the design depend on decisions made early,
.
changing a decision made early often has global repercussions and necessitates many changes to the software. Such a change is especially troublesome in a team because news of the change must be communicated to all relevant team members. Think of how difficult this must be on a project involving teams scattered across the nation at several companies. You can easily see why change is one of the great contributors to faulty and costly software.
Information hiding is a design method that helps you deal with change. When you perform information hiding, you use the principles of abstraction covere6 at Unit 2. You describe each module in terms of an interface and hidden information. The interfacL.. , es exactly what other modules can know and use: the essential infonmation. The hidden information states things no other module may assume: the irrelevant details (irrelevant insofar as other modules are concerned). This leads to designs where changes are confined to a few modules. In stepwise refinement, the early decisions focus on algorithms. In infiL:mation hidin g, they focus more on modules. Figure 2 shows the decision chain for the Reverser program derived using information hiding. Decide to separate decision chains for: - Modules that read, reverse, and write * Modules that store data Decide modules needed to read, write, and reverse
Decide algorithm
Decide algorithm
for reading input
for writing output
Decide algorithm for reversing
Decide algorithm for main module
Dccide modules needed to store data
4
Decide data structure for holding linies Decide algorithm for. holding lilies
Figure 2. Decision Chain for Infortnationt Hiding
3
Software Engineering Using Ada: Information Hiding, Workbook
Infc, -nation hiding gives you criteria you can use to judge the quality of your design: •
A module is designed well if it does not know any of the hidden information of other modules.
a
A module is designed badly if the decisions in it depend on decisions in other modules (e.g., if ReverseFile assumes stack is implemented using an array).
0
Your objective during design is to minimize the number of badly designed modules.
The ability to judge a design's quality is an important part of sound engineering practice. Once you have created your design, you must implement it. The Ada programming language has features that help you hide information as you write modules: "
You can use a package to implement a module defined by information hiding. You can use the package specification to show the interface. You can use the package body to implement the hidden information. The rules of Ada allow other packages to access any information in a package specification, but do not allow other modules to access information in the package's body.
"* You can use private types to ensure that data type representations are hidden information. Pr-vate types declare a data type name that other packages may access, but they forbid other packages from making any assumptions about the representation of the data. Here is the Line Holder module implemented as an Ada package. First, the package specification: package Line_Holder is type List_OfLines is subtype Line is
private; String(l..255);
procedure Initialize (Lines: out List_OfLines); procedure Add_LinejrToList(Line_To_Add:in Lines: in function Line_Number(Lines: return Line;
in
function Number_Of_Lines(Lines:
ListOfLines;
in
Line; out List_Of_Lines); I:
in
Integer)
ListOf_Lines) return ;nteger;
private Max_Lines: constant Integer := 10000; type Lines is array(l..Max.Lines) of Line; type ListOfLines is record Number: Integer range 0..MaxLines; Values: Lines; end record; end LineHolder;
declared private. This means other packages may reference its name and declare variables of the type, but they cannot reference its representation. This forces them to manipulate variables of type ListOf_Lines through the procedures and functions provided in the The type Lis t_Of_Lines is
4
I
Software Engineering Using Ada: Information Hiding, Workbook
*
package specification, the only ones permitted to access the representation. In this way, the designer of the Line_Holder package controls what is essential information and what is hiddep. The package's private part contains the representation of List_Of_Lines. The private part is that part following the reserved word private up to the end of the package specification. The private part declares a list of lines to be a record containing an array of lines and an integer variable that can store how much of the array is in use. Next, the package body: package body LineHolder is procedure Initialize(Lines:
out List_OfLines)
is
begin Lines.Number := 0; end Initialize; procedure Add_Line_To_ListZ(LineToAdd:in Line; Lines: in out List_Of_Lines) begin Lines.Number := Lines.Number + 1; Lines .Values (Lines .Number) := Line_ToAdd; end AddLineToList; function Line_Number(Lines: return Line is begin return Lines.Values(I); end Line-Number;
in ListOf Lines; I:
function Number_Of_Lines(Lines:
in
List_OfLines)
in
is
integer)
retutrn Integer is
begin return Lines.Number;
e:,d Number_OfLines;
end Line_Holder; The interface to the Line_Holder package gives you enough information and functionality to write the other modules in the program. The main mcdule uses it only to declare variables of type Lis -_Of_Lines.Unlike the stepwise refinement version, it has no knowledge of how a list of lines is represented, so changes to the representation won't affect the main module-or any other module. Here is the main module: writh LineHold-r, ReadFile, Write. File, Reverse_Lines; procedure Revea•_File is InputFile_Name: constant String := "input.txt"; OutputFile_Name: constant String z= "output.txt"; inputLines, Output-Lines: Liiie_Holder,List- Of_Lines; begin ReadFile(Input_FileName, Input_Lines); ReverseLines (InputLines, OutputLines); WriteFile(OutputFile-Name, OutputLines); end Reverse_File;
Software Engineering Using Ada: Information Hiding, Workbook
Notice the use of the witb clause, explained in Unit 2, to allow this procedure to reference the interfaces of the LineHolder package interface and the procedures it calls. The other modules can also be implemented as Ada procedures. For example, the Reverse module can be implemented as follows: with Line-Holder; procedure ReverseLines(OriginalLines:in Line_Holder.ListOfLines; Reversed-Lines: in out LineHolder.ListOf_-Lines)
in
begin LineHolder. Initialize (ReversedLines); for I i-a reverse I..Line_Holder.Number_Of_Lines(OriginalLines) loop Line_Holder.Add_Line_To_List( Line_Holder.Line_Number(OriginalLines, I), ReversedLines); end loop;
end Reverse-Lines;
Compare this to the stepwise refinement version. Notice how it uses the same algorithm but does not depend on how a list of lines is represented. This is especially valuable in a team, where developers need freedom to experiment with different implementation strategies and cannot risk disturbing other developers. Since other developers have made decisions based only on the interface, and since implementation strategies are hidden information, the information hiding method grants developers this freedom. Information hiding is a good design method for individuals too. You may have already encountered a situation where a change you thought would affect only one part of your program required much more work than you thought. Information hiding helps you avoid this.
6
4
Software Engineering Using Ada: Information Hiding, Workbook
*
UNIT 3: INFORMATION HIDING GROUP ACTIVITY HIDING INFORMATION
The implementation of the vending machine software was developed using information hiding and includes a module Change Calculation. The purpose of this module is to calculate the change required from the purchase of some item in the machine. The interface of this module is as follows: package Change__Calculation in type CoinValue_And_Number in record Value: Positive; Number: Positive; end record; NumberOfCoinsUsed_In_.DispensingChange: type Coin-Money is
constant Integer
3;
array(l..Number_OfCoinsUsedInDispensingChange) of CoinValueAndNuinber;
procedure CalculateChange (Price: in Positive; MoneyReceived: in positive;
Change: in out CoinMoney); end ChangeSalculation;
Procedure CalculateChange, given a price for an item in the vending machine and an amount of
money received (both in cents), returns in Change coinage that makes up the difference. For example, if the price is 60 cents and the money received is 75 cents, the contents of the array Change will be: Value
Number
Change(l)
25
0
Change (2)
10
1
5
1
Change(3)
That is, the change is 0 quarters, 1 dime, and 1 nickel. The information hidden in this module is the algorithm used to calculate how many coins of each type to dispense. Here is the implementation of the module's hidden information, that is, the package's body: package body ChangeCalculation in
procedure Calculate_Change (Price: in Positive; MoneyReceived: in positive; Change: in out Coin_Money) is ChangeToDispense: Natural; begin
7
Software Engineering Using Ada: Information Hiding, Workbook
Change(l).Value Change(2),Value Change(3).Value
25; 10; 5;
Change_To_Dispense := Money-Received - Price; Change (1) .Number := ChangeToDispense/Change ChangeToDispense := ChangeTo_Dispense mod Change (2) .Number := ChangeToDispense/Change ChangeTo_.Dispense := Change_.ToDispense mod Change (3) .Nunuber := ChangeToDispense/Change and Calculate_Change; ond Change_Calculation;
(1).Value; Change(l) .Value; (2) .Value; Change(2) .Value; (3) .Value;
Consider the following problems: 1.
Identify the hidden information in the ChangeS.Calculation module.
2.
Can you think of another algorithm to implement CalculateChange?
3.
You are to build a new version of the vending machine. This version will be sold in Germany. The German m, ietary system differs from that of the United States. It is based on the Deutsche Mark (DM). There are 100 pfennigs in a DM. Germany has 1 pfennig, 5 pfennig, 10 pfennig, 50 pfennig, 1 DM, 2 DM, and 5 DM coins. German vending machines don't dispense as change paper money or coins less than 10 pfennigs. German vending machines dispense drinks, but dispensing food hasn't caught on in Gmrnany or most other European countries. Drinks cost anywhere from 50 pfennigs to 1.2 DM. Create a new version of the Change-Calculation module that calculates change for a machine that receives and dispenses German money. Make as few changes to the interface as you can.
4.
Why is it important that you change the interface as little as possible? HOMEWORK
1.
Adapt the change calculation module of the vending machine for use in another country.
2.
A rational number is a number that can be expressed as the ratio of two integers. Use information hiding to design and implement a program that reads two rtio... numbers, adds them, and prints the result: a. Decompose the problem into a set of modules. For each module, state its interface and its hidden information. Describe the interface as an Ada package specification; describe the hidden information in English. b. Implement each module. Represent a rational number as a pair of integers. c. Change the implementation of rational numbers to a single floating-point value. What are each implementation's relative advantages and disadvantages? In what programs would you use one or the other?
Software Engineering Using Ada: Information Hiding, Teacher Notes
*
TEACHER NOTES FOR GROUP ACTIVITY The package Change_..Calculationpresented here illustrates how you can u;e the programming
languageAda to implement modules desiSned using the information hiding design method. The package specification is the module's interface. It provides a single procedure that another module may use to determine what coins, and how many of them, must be dispensed to provide a person with changefor their purchase. The package also has several data and type definitions. This is usual in information hiding: developers will accompany the proceduresand functions with data types that support their use. 1.
Identify the hidden information in the Change_Calculation module. The algorithm is the hidden information, so it's the implementation of calculatechange.
2.
Can you think of another algorithm to implement CalculateChange? Here's one. Though slightly more complex than the first algorithm, it's actually easierto change when you do activity 3. The reason is that the originalalgorithm made a design assumption that change was always dispensed using three coins. procedure Calculate_Change (Price: in Positive; Money-Received: in Change: in ChangeTo-Dispense: Natural; begin Change(l) .Value Change(2).Value
positive; out Coin-Money) is
:= 25; := 10;
Change(3) .Value := 5; ChangeTo_Dispense := MoneyReceived - Price; for C in Change'range loop Change(C) .number := ChangerTo-Dispense / Change (C) .Value; ChangeTo_Dispense := ChangeToDispense mod Change(C).Value; end loop; end CalculateChange;
InAda, you use the notation Change Irange in aforloop to indexeach value in the arrayChange. In this case, the loop index variablec assumes the values 1, Z and 3, in that order. 3.
0
You are to build a new version of the vending machine. This version will be sold in Germany. The German monetary system differs from the United States'. It is based on the Deutsche Mark (DM). There are 100 pfennigs in a DM. Germany has 1 pfennig, 5 pfennig, J0 pfennig, 50 pfennig, 1 DM, 2 DM, and 5 DM coins. German vending machines don't dispense as change paper money or coins less than 10 pfennigs. German vending machines dispense drinks, but dispensing food hasn't caught on in Germany or most other European countries. Drinks cost anywhere from 50 pfennigs to 1.2 DM. Create a new algorithm that calculates change for a machine that receives and dispenses German money. Make as few changes to the interface as you can.
9
Software Engineering Using Ada: Information Hiding, Teacher Notes
Here is one answer.The lines in italicsare the lines that differfrom the original.The algorithm now calculateschangefor a machine that dispenses coins from l Opfennigs to 2 DM. The interface had to be changedslightly to support this, since the U.S. version assumed that 3 ýTpes of coins (quarters, dimes, andnickels) were dispensed,whereas the German version dispenses 4 types (1Opfennig, 50 pfennig I DM, and 2 DM). package Change_Calculation in type Coin_Value_AndNumber is record Value: Positive; Number: Positive; end record; Number_Of_CoinsUsed_In_DispensingChange:constant Integer
4;
type Coin-Money is array(l. .Number_.Of_Coins_Usedln_DispensingChange) of CoinValuejAndNunmber; procedure Calculate_Change (Price: in.Positive; MoneyReceived: in positive; Change: in out CoinMoney); end ChangeCalculation; package body Change_Calculation is procedure CalculateChange (Price: in Positive; Money-Received: in positive; Change: in out Coin-money) is ChangeTroDispense: Natural; begin. Change(1).Value 200; Change(2).Value 100; Change(3).Value 50; Change(4).Value 10; ChangeTroDispense := Money-Received - Price; Change (1) .Number : = Change-ToDispense/Change (1) .Value; ChangeToDispense := ChangeToDispense mod Change(l) .Value; Change (2) .Number := ChangeTo_Dispense/Change (2) .Value; ChangeToDispense := ChangeTo_.Dispense mod Change(2) .Val.ue; Change (3) .Number : = ChangeToDispense/Change (3) .Value; ChangeToDispense := ChangeToDispense mod Change(3).Value; Change (4) .Number := ChangeTo_Dispense/Change(4) . Value; end Calculate_Change; eni Change_.alculation;
Why is it important that you change the interface as little as possible? Suppose you arepartof a team andare writing a module that uses this module. You will have made some design decisions based on the interfaceyou expect. If that interfacc changes, you may have
to rethink your decisions.
10
I
Software Engineering Using Ada: Information Hiding, Teacher Notes
You will often find you cannot avoid making any changes to a module's interface. HIowever, you can plan ahead when you design a module~by thinking of the things that are likely to change. This is partof what information hiding is all about. The things you think are most likely to change are the things you hide behind an interface. You may have to make certain parts of the interface susceptible to change. Here, the number of coins in the monetary system had to change. However, by making that value a constant, you can let other modules rely on the constant ratherthan an a literal. In this way you can lower the likelihood of inadvertent effects.
Software Engineering Using Ada: Information Hiding, Teacher Notes
This page intentionallyleft blank
12I
12
Software Engineering Using Ada: Information Hiding, Teacher Notes
*
TEACHER NOTES FOR HOMEWORK Students may do the homeworkproblems in any programminglanguage,although usingAda will help them separateinterfacefrom implementation. If they use Pascal,encourage them to use units (ifyour compiler supports,them.)
1.
Adapt the change calculaton module of the vending machine for use in anothe.r country. In France,the monetary system is based on the French Franc. The coins are 1, 5, 10, 20, and 50 centimes, and 1, 2, and 5 Francs;100 centimes equals I Franc.Frenchvending machines dispense coinsfrom 20 centimes to 2 Francs,inclusive. Products cost between 1.2 and 8 Francs. package Change_Calcultion is Number_OfCoins_ToDispense:
constant
Integer := 4;
end ChangeCalculation; package body Change_Calculation is procedure Calculate-Change (Price: in Positive; Money.Received: in positive; Change: in out Coin_Money) is ChangeToDispense: Natural; begin Change(l).Value := 200; Change(2).Value := 100; Change(3).Value : 50; Change(4).Value
:= 20;
Change ToDispense
:= MoneyReceived
-
Price;
Change (l).Number := ChangeToDispense/Change (1).Value; ChangeToDispense := ChangeToDispense mod Change(l).Value; Change (2) .Number := ChangeTo_Dispense/Change (2) .Value; ChangeToDispense := ChangeTo_Dispense mod Change(2).Value; Change (3) .Number := ChangeToDispense/Change (3) .Value; Change ToDispense := ChangFTo__Dispense mod Change(3).Value; Change(4) .Number := ChangeTqo_Dispense/Change(4) .Value; end Calculate-Change; end Change-Calculation;
2.
A rational number is a number that can be expressed as the ratio of two integers. Use information hiding to design and implement a program that reads two rational numbers, adds them, and prints the result: a. Decompose the problem into a set of modules. For each module, state its interface and its hidden information. Describe the interface as an Ada package specification; describe the hidden information in English. It's important that the students try to design the modules before plunging into the implementation. They should try to come up with the answer to this question before
13
Software Engineering Using Ada: Inironation Hiding, Teacher Notes
tackling Partb. However, it's also okay if they don't get the correct answer on the first try. Engineering design is an iterative activ;ty. There are two modules, Rational-Numberand Main. RationalNumberhas the following
interface: package Rational_Number is type Rational in private; function RationalNumber(Numerator:in Denominator: in
Integer; Integer)
return Rational; function Add(rl, r2: Rational) return Rational; function Numerator(r: Rational) return Integer; function Denominator(r; Rational) return Integer; private type Rational is record Numerator: Integer;
Denominator: Integer; end record; end Rational]_Number;
The hidden informationof thl module is the representationof rationalnumbers and the algorithms used by the functions that manipulate them. The main module has the following interface: procedure ReadSum_Arid_PrintRational_Numbers;
The hidden informadon of this module is the algorithm it uses. b. Implement each module. Represent a rational number as a pair of integers. The following implementation takes the trouble to normalize rationalnumbers after each operation-thatis, it divides the numerator and denominatorby theirgreatest common divisor,If your studentshave not yet encounteredthis algorithm,you may want to provide it for them.
I1 14
Software Engineering Using Ada: Infomialion Hiding, Teacher Notes
package body RationalNumber is ------
This package implements rational numbers as pairs of integers. The advantage to this scheme is that rational numbers are represented exactly. The disadvantage is that numbers must be normalized after creation and each arithmetic operation, requiring some extra time.
procedure Normalize(r: in out Rational) is Numerator, Denominator: Natural; Remainder: Natural; begin Numerator
:= abs(r.Numerator);
Denominator := abs(r.Denominator); while Denominator /= 0 loop
--
Find the greatest common
--
divisor of the numerator and denominator using
--
Remainder := Numerator rem Denominator; -- Euclid's Numerator := Denominator; -algorithm. The algorithm Denominator := Remainder; -ends with numerator end loop; -holding the GCD.
r.Numerator := r.Numerator / Numerator; r.Denominator := r.Denominator / Numerator; end Normalize; function RationalNumber (Numerator: in Denominator: in return Rational is r: Rational; begin r.Numerator := Numerator; r.Denominator := Denominator; Normalize(r); return r; end Rational-number; function Add(rl, r: Rational; begin r.Numerator
Integer; Integer)
r2: Rational) return Rational is
:= rl.Numerator*r2.Denominator
+ r2.Numerator*rl.Denominator; r.Denominator := rl.Denominator * r2.Denominator; Normalize(r); return r; end Add; function Numerator(r: Rational) begin return r.Numerator; end Numerator;
return Integer is
function Denominator(r: Rational) begin return r.Denominator; end Denominator; end Rational_Number;
return Integer is
15
Software Engineering Using Ada: Information Hiding, Teacher Notes
This implementation of the main module goes through the rigamarolenecessaryto instantiatethe genericpackages neededfor intejerinput and output. That's not importantfor the purposes of this assignment.Rather,have the students concentrateon the algorithm. with Rational_Number, TextIO; procedure ReadSumAndPrintRationalNumbers is package Integer_.0 is now Text_IO.Integer 1O(Integer); rl, r2, Sum: RationalNumber.Rational; Numerator, Denominator: Integer; begin Text_IO.put("Enter the first number: "); IntegerI0.get (Numerator); Integer_10.get(Denominator); rl := Rational_Nunmber.Rational_Number(Numerator, Denominator); Text_IO.put("Enter the second number: "); Integer_IO.get(Numerator); Integer_1O.get(Denominator); r2 Rational_number.Rational_number(Nunerator, Denominator); Sum Rational_Nwuber.Add(rl, r2); Text_IO.put("The sLm is 1); IntegerIO .put (Rational_Number.Numerator (Sum)); TextIO.put('/'); IntegerIO.put (Rational_Number.Denominator (Sum)); end ReadSum._And_Print_Rational_Numbers;
c. Change the implementation of rational numbers to a single floating-point value. What
are each implementatioil's relative advantages and disadvantages? In what programs would you use one or the other? The package specification is identical, except that the representation of Rational changes. Replace the lines: type Rational is record Numerator: Integer; Denominator: Integer; en6 record;
with: type Rational is
new float;
HT,,.re is the pckage body: package body RationalNumber is ------
This package implements Rational numbers as floating-point quantities. The advantage to this scheme is that it is very fast for performing arithmetic operations. The disadvantage is that the numerator and denominator must be approximated rather than computed exactly.
Numnber_Of_Denominators:
constant := 10;
Denominators: constant array(l..Numuber_Of_Denominators) (1, 2, 3, 5, 7, 11, 13, 17, 19, 23);
of Integer
16 - --•
•- I:•~lli :,
,lnu
• n
Ull '
•'1
1"I '•|
I-
I
i Il
"
'il
I
t ll
nn
I
*AM¥1
Software Enýineering Using Ada: Information Hiding, Teacher Notes
function Rational_Number(Numerator: in Integer; Denominator: in Integer) return Rational is begin return Rational(Numerator)/Rational(Denominator); end Rational_Number; function Add(rl,
r2: Rational)
return Rational is
begin return rl+r2; end Add;
--
Compute the numerator and denominator of r. The algorithm is to choose for denominator the value in the denominators
--
array such that numerator = floor(r*denominator)
--
numerator/denominator is
--
value of denominator in
--
and
closer to r than for any other the array.
procedure ComputeNumerator_And_Denominator_Of_Rational( r: in Rational; Numerator, Denominator: out Integer) is d, n: Integer; dprime, nprime: Integer; begin d := Denominators(Denominators'first);
n Integer(r*Rational(d)); for i in Denominators'first+l dprime
Denominators'last loop
..
z= Denominators(i);
nprime z= 1*iteger(r*Rational(dprime)); if abs(Rational(nprime)/Rational(dprime) < abs(Rational(n)/Rational(d) d : dprime; n := nprime;
-
r)
- r)
theo
end if; end loop; Numerator := n; Denominator := d; end ComputeNumeratorAnd_DenominatorOfRational; function Numerator(r: Rational) return Integer is d, n: Integer; begin ComputeNumerator_And_DenominatorOf_Rational(r, return n; end Numerator; function Denominator(r: Rational) d,
n:
n, d);
return Integer is
Integer;
begin Compute_NumeratorAnd_Denominator_OfRational(r, return d; end Denominator;
n, d);
end RationalNumber;
17
Software Engineering Using Ada: Information Hiding, Teacher Notes
The differences between the two implementations may be summarized as follows: -
The first implementation is slower It must execute the normalization operation after creation and every arithmeticoperation.Moreover,adding two rationalnumbeirs using the first implementationrequiresthree multiplicationsandone addition, whereas addingthem using the second implementation requires only a single addition.
-
The second implementation is less exact. The first always representsa rationalnumber as the ratio of two integerquantities, which is the definition of a rationalnumber The second, which uses a floating-point value, represents a fixed number of significant digits. Furthermore,its algorithmfor determining the numeratorand denominatoris accurate only to two significantdigits.
You would use the first implementationinprogranswhere accuracy is of more concern than speed. You would use the second implementation when speed is of more concern thanaccuracy. You must alsoassess what operationsyou will use mostfrequently. The first implementationwill be bothfaster and more accurate ifyou invoke the numeratorand denominatorfunctionz more often than the additionand creationfunctions.
i 18
'
I*
U
-
0
b1
0
0)
0) C
.5) C ILl 6)
0
c)c
(c
'0
g>%
co
002( C:
M-
CU.0
0o = 4)
_d
(DD
0~
4D W UU)
((D D
~
0)C
EL
oA'
'
Cr
con
ou
x
-oD 0
Z
'D (-
a
%n
coI~L
co
ýO a
vo
-a ,U >C-'
O~CU
2 U) .0L
oICD4:
Cl)
co
a).3 c co
C
--
Cu 4-
Q
U)~>
9
co S
)
_
)
.
cc$
M-6.
NINO,
0)0
a)E
0o
So
CD
+cc- M Cl
CV
CDC
0~..I..
oz
0
c0
ZCD 75
ca -a 00
c0
0
Z
)
E
CC~i.A a)
>na -~ZC
>o.E a2D (D
c
( .0) ) U~ ) 0) a)
CD
C
_
0
:) E 2-
(0
.
0
(0
3
(1)
c Cu.S.
uD C
(D
_:
E0 Cw
0 %6-.~
E
(D P~
w 0
CL M o (C C 'C a) (30)
75 :L'-
L
C.
0)
*(~.r-) - 0
cd
co
0) CD
.CDc
.c% 4-,
28
a)
a)
0
U) 0
(0O)2E a)
~
W~ 05
0
,o E
g
Cu
*
JOL0L).>-
0
0o
Da'
Dl) ~2~~(a~
CO 0)
~co~cu
0() a
C 22
r-
Cc2)O 0)
CD CLco
~
Cu)
Cu
W Q)EC
-=C
2
0
u~oeu)
Cu)
U) =~I20
w
cm
a
l0
U)
CL
E
C
00 0 U)
0
L
0 Lu.
(D
Lu.
U-
as 0)
LL
LEr
L) C) 0)0
0
00)E
0m
E
-
=1 >%0 00-0
5 0)-
0
a)E0 0)
>
>
0)))>-
FS0
($
0
E*
0 >)
E)
(8o D
-
04
)
-CL
0
0
="
6
v 4-
w
0
0
00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ci
o
.
z W
E~CL C. o
a) "
.C0
()
a' a .- o ,,0 _-, -~4 .,._ filOC >..~ 1 .S (T 'Ch .f(nl = , 0•0 -- 0-(n" .-C: cc 0,..' EE 4'
E
"
(DDa
>%
. oc
,,,-o=
-
0 U) (z
0
.,
.,,_
ov.
co
0
. o(ca)> c (•,'. 0 Uo crm
:3 Co
0.=•
CD
o
0.••. C.
E.a)
0
U,
E
:%
IV)O •
a)
-,g
•-(U
:3 (D•
E)
=CU
0-
0~(
J - > C5o2-o-
o
0_
-" C o0
a E-2
AR', ,-.-a) z.x
0C
o
E
(D
0OCD
E
"-
oa 0=
0
00
CO.'""O= o 0 .0-CU>cis 70 :S
- 4
~
-
0
Eo
,
(D
*E
0c
010.0 a)C,>~I
4 9
co
>'
0
0
.
-o
C:!c -
(n
-o
*a) C-.
Co -~
CL
13 4)
C WOMEN(I cc
Iu)
0
o%
0)M ZV.> '0
CUL
*0 o *
(
0)
D0.0)
0)
MC0 ME
00 0E 0.CX.O
00
CU 0)MM
04-Z
0
75 0 .C r-C
. a
>"*1='
=C )
U)
4
a(
o*Z
0
co0
0
0)
0)
Cll)
CD
.0
W
0
0c
15
(D) a)
VcC
0
0)
0
E
u 0
:
C
o
..
a)
a
a
0
2C
cn 0 r_
CO 0 M 00
-S
a
ca
0) 0 2
CL
cm
-0~
CO
=C 00
0
_co
Co
(DX-a)
CDE CIS Z
0)
-
~
~
0 70
0C :3) O
.4
:3~
42
00
Da)
0
OVU
-0
U~Ž.CC)
Ca)
a
a)
CDL
_,l
S0. 0)
C-o C) OL.
L..
0
00
0%
Z CO ~20
a)
>% c0.C0)C Cl)
CO
U)
01
0
m cn
_____U)______D_______________________0_______t___
0 c
CD C
,Wo
o&5
(D=
0___
CL
02 cc-I
0 0
@0)) O
>
MOM
.5--
0)
ca
0) 4)
to
U)
I 1
a)l tR
4)
U9
CD a)
co
)
-
0
cz 00
*
0 CL
0a
2w0
c
Cu
0l
'm
UY
Da) 0c
0
CM 0C
0
r
C
C
0 CL
cau~
u-
_
)-0 0u c_ )
_U
a) 0
E
)
E2) V0. a)) A cm 0.E
cd
oE E
0 .0
C)~ .alz ~
0-
C
C2)
006
U). )CD
a)
Eo
n0)
~co
0
ClaCu 0
00
cU -
-
0) CD 0~ Cu Cu
0d
=.-U) 0
00
ECUaD~~U) 6'5 0 :&00
O:.
CNe
0 -
0.
'0
= -OCL EIw
00
00
E*-)u~ 04 - o0) w)
CD L4- CL CO~
C.(D0
5UU)u EjU,
id
0
a)
-5 S
CfLa.
lE
-
=-6s-
0)
Zý0E-0
U)C.
0
-.
WO
>
) a)
-.
)
-0
1-
01 E
75 w
a)
-a a a
.'
"u
.~ca
00o
E E
>2
q..r
0 CD
LM
glo JCC
E
*
0
0
Softwarc Engineering Using Ada: Reuse, Workbook
*UNIT
4: REUSE UNIT SUMMARY
As you develop software, you will often find that you need a module that offers functions and data types similar to, but not exactly matching, one you have developed in the past. The more experience you gain with software, the more you will find this to be true. You will also find that other people have developed software you might be able to use. In other words, no program is totally unique. It solves' a problem related to problems that have already been solved, and its modules and structure resemble, in part, modules and structures of existing programs. You should try to reuse existing software whenever you can. Studies have shown that in many programs, especially larger ones, 50% of the lines of code can easily come from existing programs. Reuse of 70% of the code is not uncommon. Since a software developer produces an average of 40 lines of code per day over the cuurse of a project, it's easy to calculate just how quickly the savings will add up.
O
Unfortunately, reuse is harder than it might seem. You'll find the primary reason is that you developed your modules for use in a specific program. When you try to use them in another program, you often realize you need something slightly different: a function must operate on a string rather than an integer, for instance. You may find that writing a new module from scratch is easier than modifying an existing module. There are several things you can do to improve the chances that a module will be reusable. One is to use generic packages. When you write a generic package, you declare generic parameters that specify the different ways you expect you might want to use the package. You can then instantiate the generic package by providing values for the parameters that meet the needs of specific programs. For example, you can use Ada generic packages to rewrite the Line-Holder package so it can hold integers, strings, or any object that is a valid Ada data type: generic type Item ia private;
package Holder in type List is private;
procedure Iriitialize(Items: out List); private Max_Values: conutaut Integer := 10000; type Items iA array(Integer range I..Max_Values) type List is record Number: Integer range 0..MaxValues; Values: Items; end record; end Holder; *
If you then declare a data type representing a line: subtype Line is
String(l..255);
of Item;
Software Engineering Using Ada: Reuse, Workbook
you can create a Line_Holder package that behaves identically to the one in Unit 3 using the following generic instantiation: package Line_Holder is now Holder(Item => Line);
Because Holder is a generic package, you can use it to hold objects of any type. For example, you can use the following generic instantiation to hold a list of integers: package Integerjolder in new Holder(Item => Integer);
The Ada compiler cranks out a new package based on the parameters to the generic instantiation. It's as if you took the Holder package and substituted Line or Integer everywhere Item appears. See Figures 1 and 2, drawn from the Ada code on Slide 4-6. In each figure, the generic Holder package on the left side, with its generic parameter Item, is instantiated to yield the package on the right. Strlng(1l.255 typo list; Item
procedure Initialize;
type List;
51 I-n
procedure Inlttalizm;
' ...
i/st:
I~
1
1o,0o0
Une
Data types and numeric values are examples of parameters you often use to make a module more reusable. Ada has many kinds of generic parameters. Figures 1 and 2 illustrate a generic type parameter. You can also write generic packages with generic formal object parameters. A generic formal object is a parameter that's a constant value, such as an integer or a character. For example, you could add a parameter Max...Values that controls the maximum number of values a holder can store. See Figures 3,4, and 5, drawn from the Ada code on Slide 4-8. A second generic parameter, MaxValues, has been added to the Holder package. This parameter lets you specify the maximum number of values an instantiation of the Holder package can store. You can now control both the type and size. Figure 3 creates a package that stores 1,000 lines. Figure 4 creates a package that stores 30 integers. Figure 5 creates a package that stores 50,000 integers. A generic type parameter can be any valid Ada data type, even one declared from a generi.. instantiation. Figure 7, drawn from the Ada code on Slide 4-9, illustrates this point. Here, the item used in the lower generic instantiation is of type List from the package Students, which was instantiated from Holder.
2
Software Engineering Using Ada: Reuse, Workbook
type List;
I Item
procedure Initialize; List: 1 Integer
,
9 Integer 3 Integer
Item
Initialize;
List:
Integer ...
2t
tList;
Gnrc,
n
lO000 1
1
Vroeedura
Figure 2. Generic Instantiation of the Holder Package With Item-> Integer Pa-,'
Sring(1.,255)1,0•
UýMInstantiation
type list, ae Max Values 10:0 kprocedure Initializspcal
Anothr
SM _List: Item
1 Line
,41
Line 5 -Line -1
typo List;
List:
Generic
[Tem I
Ins tantiation /1,O00
"'Um .
,
9991
Ln
I
in
Max-Values
Figure 3. Generic Instantiation of the Holder Package to Hold 1,000 lines
Another useful kind of generic parameter is the generic range parameter. It is a special case of the generic type parameter, where the type you provide is a subtype of integers. Using subtypes helps you overcome the situation in Figure 7, where to index calendar years you must create a new data type to YearIndox subtype, in th• lower generi ^ A 11-0 ... instantiation to create a holder module whose indexes range from 1980 to 2029. AA
SU.
You can also improve the chances that a module will be reusable by spending some extra time thinking about reuse as you develop the module. Ponder the functions that the module offers. Think about what is essential to the module and what is incidental to the program for which you are developing it. This will help you realize what generic parameters are appropriate.
0 3
Software Engineering Using Ada: Reuse, Workbook
If you follow this advice, over time you will build up a "library" of reusable modules. You will find that your software development process automatically incorporates reuse. As you design your software, you will consider what modules are in your library and base your design on what you can reuse, realizing that reuse will save you considerable amounts of time.
30 -Fgure4.Gneric Inte
n
o talues
Max Values
to
Item
•
it
rocedure Inittialize,.
procedureednitializeu,
[!n.
istI
Generic
~~~type
Integer
0
tantato
MaxValues
S
g
9
4
Ust;
1t
Figure 4. Generic Instantiations of the Holder Package toHold 30 Integers
type Li1st;
hidingd Raima
esi
rocedure Initial3ze-,
Ie4
procedure Initializ 7eeercI .. Fist:
c
.
Integer
ding.
was nwhc thue a dapaini psil.Tissprto Yo Man doathisby hidingho th senilfctoswrbthw
;c-n49,9991
ofntefac a
IntegerI .ndthidenifrmtocme
Ingntheginerfae
h
xc
Figure 5, Generic Instantiation of the Holder Package to Hold 50,000 Integers
Reuse goes hand in hand with the information hiding design method covered in Unit 3. 7To create reusable software, you must make it adaptable to a range of situations in which it will likely be used. You can do this by hiding how the essential functions work, but showing, on the interface, the exact ways in which the adaptation is possible. This separation of interface and hidden information comes directly from information hiding.
4
Software Engineering Using Ada: Reuse, Workbook
SName
.q•d••
ICSý..ade-
type List; procedure Initialize;
istory_LGrade S~1
,,_________
Student Index
Math Grade
Index
Item
List: Student:
Math Grade CSOrade
.104S-
Index
AHistoryGrade
Item procedure Initialize; Lis1
Name Generic
EE 1Max-Values
Instantiatonso List;
ityre
Yerqdxtpe
0Suet
I.,i.•t:U
M
Year Index
Item
Inde~x~tm•
procedure
ath:rd
typo List; procedure Initialize; List: 1980
Stude~nt H-older:
50 [ae.. eag
•
2029 Student Holder:
type__________
Initialize;
G1 '" 1Max-Values
Index
Grade Nat e Grade Ne
I Niunc, Gradesl Name, Grades
Instantlatlon
Figure 6. Instantiating Student Grades and School History Using Generic Range Parameters
0
Software Engineering Using, Ada: Reuse, Workbook
Item
Max-Values
List:
Stu1cStudent:
1NNamerae M
typo___List;__
50
poedureIntaie
ame, Grades
Student.Hldr
IC'IntnlalnName,
I..R 7
Fiur
7.m
Instantiating
Stuen
GradesadShoHity
Its su6 6
a-ausHitr-rd
____________________________
Software Engineering Using Ada: Reuse, Laboratory
LAB UNIT 4: REUSE LABORATORY SPECIFICATION NOTE: This laboratory is not being produced for the pilot offerings. The laboratory will appear in a later version of the course, based on comments received from the teachers of the pilot offerings. Ibis specification provides a definition of the current vision for such a laboratory. Because the laboratory has not been built, not all issues have been resolved. Unresolved issues are shown in italic text. PART 1: BACKGROUND In this laboratory, you will assemble vending machine software. You will not write this software yourself; you will use the reuse techniques you learned in your lecture to create it. You will work in groups, jointly reusing and developing the software. Suppose you are an employee of the Press 'n Gobble Vending Machines Company. One day, your sales department informs you that it has located two potential markcts fui the vending machines your company builds. However, none of Press 'n Gobble's current machines quite fits either market. Management has decided to develop new ones and assigns you to develop the software the machines will need. Here is a description of each machine: 1.
The first machine is to be sold in the United States. It will dispense a variety of food products. It will look as shown in Figure 8, Items in the second row cost 65o. All other items cost 55¢.
11
12
13
14
22
21
15
23
U
I Selection
31
41
FI~i i~i~
32
42
33
43
34
44
35r'
I
Dollar
_JL!
45 1
Figure 8. A Food-Dispersing Vending Machine
__
7_.
.
.._I
Software Engineering Using Ada: Reuse, Laboratory
2.
The second machine is to be sold in Germany. It is shown in Figure 9. This machine is to dispense hot beverages: coffee, decaffeinated coffee, tea, and espresso. Because it dispenses only a few items, it does not have a numeric keypad for selection. Instead, each item has a button; you push that button to get the item. Of course, German labels will be substituted for the English ones when the machine is placed in final production. You can insert 10 pfennig, 50 pfennig, 1 DM, 2 DM, or 5 DM coins. The machine dispenses change using 1 DM, 50 pfennig, and 10 pfennig coins.
Hot,,Drinks,..... Coffee
Decaffeinatud Coffee
Espresso
Tea
50 pf
50 pf
1.2 DM
80 pf
'., j:
Pu.sh,
Push . . ..
Push
~,
Push
..
1
Coin Return
Figure 9. A Drink-Dispensing Vending Machine
Your assignment for this laboratory is to generate the software for bot'- vending machnes. You will do so by choosing the necessary software modules, as explained in the exercises below. You must compile and link these modules. You can then run the software.
THE SoFTwARE DESIGN
Press 'n Gobble's software developers maintain an extensive, well-organized reuse library of the modules they have developed over the years. Furthermore, they have developed a general design for vending machine software. When presented with the requirements for a new vending machine, theyl can quickly determine the modules they need. Every program they develop always has the modules listed in Thble 1.
8
Software Engineering Using Ada: Rems, Laboratory
Table 1.Software Moduleos Used In All Press 'n Gobble Vending Machines Module Name Change Return Button
Coin Return Coin Acceptor Item Dispenser Money Accumulator
Item Selector Input Event Handler
Change Calculator
,Price
Information
Holder
Module Description Signal that the money the person has entered so far is all to be returned. The hidden information of this module is how it is determined that the button has been pressed. Dispense a selected amount of money, in coins. The hidden inf.rmation of this module is how the hardware that dispenses coins is activated. Accept coins and provide to the software the value of the coin. The hidden information is the means by which it is determined what coin was entered. Dispense a product to the person. The hidden information of this module is how the hardware dispenses products. Maintain a-record of how much money the person has entered so far. The' hidden information is the means to calculate and represent this information. Signal a selection. The hidden information of this module is how it is determined that the person has pressed the buttons to make a selection. Collect and respond to the signals issued by other modules. The hidden information of this module is the algorithm for collecting and responding to signals. Determine the amount of change needed for a purchase. The hidden Information of this module is the algorithm for calculating change. Maintain the price for items dispensed by the machine, and allow determination of whether a specified amount of money is sufficient to purchase a specified item. The hidden information is the representation of !he prices and the algorithm for determining whether the purchase price is enough. Maintain a list of items. The hidden information is the representation of the list and the algorithms for accessing it.
The details of some of these modules may vary between machines, but a form of each module exists in the software of any vending machine Press 'n Gobble sells. This list of modules is not. ntended to be complete, just illustrative. They ivere derived using information hiding. Moreover,many of them are used in both vending machines. This module sharing is the primary requirementfor any design. Press 'n Gobble's software library has other parts too. These parts are only needed in certain vending machines, as described in 'lhble 2. 'Thble 2. Software Modules in Specific Press 'n Gobble Vending Machines Module Name Bill Acceptor
Money Display
Module Description Accept bills, and provide to the software the value of the bills. The hidden information is the means to determine what bill was entered. Display an amount of money. The hidden information is the algorithms used to activate the display.
Iiiclude If... The vending machine is to accept both coins and bills. The vending machine is to display the amount of money the person has entered so far,
9
Software Engineering Using Ada: Reuse, Laboratory
PART 2: LABORATORY EXERCISES EXERCISE 1: UNITED STATES VENDING MACHINE
You are to create the software needed for the vending machine to be sold in the United States. You must perform the following steps: 1.
Read the description of the food-dispensing vending machine on Page 7.
2.
Determine the modules you will need for the vending machine's software.
3.
Assign a set of modules to each member of your group. 'You should bear in mind that some modules are larger than others and partition them equally across your group so everyonie has approximately the same workload. Use the figures in the last column of Tables 1 and 2 as a rough guide to the relative time each person will need for each module. This column isn 'tin placeyet and can't be until the software is written. We shall need to time each module's compilation and prepare the figures based on that information. Note that Steps 1 through 3 would make an e~xcellentprelaboratoryhomework assignment.
4.
Each person must perform the following steps. See the accompanying write-up on using the laboratory for instructions on how to do so. a. Create a directory in which to work with her or his assigned set of modules. b. Copy the modules assigned to her or him from Press 'n Gobble's library of reusable modules to the directory created in Step a. c. Write generic instantiations for the following modules: ... We shall ask the students to write a few generic instantiations,just so they get the feel of adaptingreusable modules to fit a specific need. We shallprovide them with templates, and we shallprovide the teacher with the answers. d. Create an Ada library. Thiis is assuming that the Ada compiler does not support concurrent compilation using a single libraj. e. Link her or his library with the library of everyone else in their group. f. Use an Ada compiler to compile her or his modules. There is on-. complication to Step 4.f The modules are represented as Ada packages. As Unit 1 mentioned, Ada packages must be compiled in a particular order. You and your fellow group members must observe the rules in Table 3 as you compile your modules. Table 3.Compilation Dependencies Among Press 'n Gobble Software Modules Module Name
This column lists a module that's dependent on at least one other module.
10
Compilation Dependencies This column lists all dependencies.
Software Engineering Using Ada: Reuse, Laboratory
5.
Your group is now ready to create an executable program. The person who compiled module main program must invoke the Ada linker.
You may now execute your program, using the following input data: .... After you have finished executing your program, answer the following questions: 1.
What communication difficulties did you encounter and how did you overcome them?
2.
How would you compare this to your experience with software development?
EXERCISE
2: GERMAN VENDING MACHINE
Repeat Steps I.through 5, this time creating software for the vending machine Press 'n Gobble will sell in Germany. When you have built the software, execute your program, using the following input data:... Now answer the following questions:
0
1.
How many modules from the first assignment did you reuse without any additional work?
2.
How many modules from the first assignment did you reuse by performing different generic instantiations?
0 11
Software Engineering Using Ada: Reuse, Laboratory (Instructions)
PART 3; INSTRUCTIONS FOR LABORATORY NotE: This laboratory will ultimately be available for a variety of platforms (IBM PC, Macintosh, etc.). This write-up, which describes how to use the laboratory, is specific not only to each platfonn but to the institution in which it is used. A separate version of this write-up is therefore needed for each platform, and instructors must tailor it to their own institutions. In all cases, students must: -
Have an Ada compiler
-
Be able to create files
-
Be able to read files created by other students
-
Be able to read a set of files created by the instructor
For simplicity's sake, this write-up is written as if the laboratory were being run in the following environment: Each student has access to an IBM PC (or compatible) computer with a 286 or compatible processor. -
Each PC is conneLced to a file server on drive S.
-
Each student has permission to create files in a subdirectory of drive S.
-
Each student can create and edit text files (Microsoft's edit application or most Pascal compilers would do).
-
Each student has access to an Ada compiler.
As in the laboratory descriptions, unresolved issues appear in italic text This write-up describes how to use your computer to perform the vending machine laboratory exercises. The emphasis is on Steps 4 and 5, since these are the steps that involve using the computer. 1.
To perform this step, you must log on to your computer. Then perform each of the following steps:
a. Crc ty eaa
So
your assigned set of modules. For this
.,
e o laboratory, you will work in the directory s: \ adalab. Create a directory whose name is your last name: director.y
In
which
..
-
-odu.
C: \>S: •: \>mkdir \ adalab\yourname S: \>chdir \adalab\yourname
b. Copy the modules assigned to you modules from Press 'n' Gobble's library of reusable modules to the directory you created in Step L.a. You will find these modules in the directory S: \adalab\pressgobble_modules. The modules are in the following1 files:
12
Software Engineering Usintg Ada: Reuse, Lboratory (Instructions)
Here we include a table listing all the modules shown in the tables in the laboratory.Foreach module, we state the file or files holdingits code. S \adalab\yourname>copy \adalab\ filel
.ada
Perform a copy command for each module assigned to you. c. If you have been assigned moduleX, you must write a generic instantiation of package Y named Z. A generic instantiation of Y has the form: package
Z is
new Y(PI => V1,
P2 => V2);
Use text editing applicationto create a file named z. aria that contains the above line. Use valuel for Vl and value2 for V2. d. Create,
Ada library, using the following command: S: \&ada ab\yourname>mklib
e. Link your library to that of other members of your group. For example, ifyoux' partners are hername and hisname, issue the following two commands: S \a&da1ab\youraam*, l.nklib s: \adalib\hernane\ada. jib S:\adalab\yourname>linklib s :\adalib\hisname\ada. lib
f. Compile your assigned set of modules. For instance, if you are assigned modules stored in files x. ada, y. ada, and z. ada, issue the following commands: S \adalab\yournams>ada x. ada S : \ada&1b\youzrams>ada y. ada S : \a&dalaab\yourname>ada z.ada
Be sure to observe the dependency rules! If you do not, you will get an error message
from the compiler: The error message when a package can't
2.
be found.
Whoever in your group was assigned to compile the file main. ada must now link together all the modules: S: \adalib\yourname>.link main
This will produce a file called main. exe. You can execute this file by typing the command: S :\adalib\yourzame>main
13
Softwaic Eagineering Using Ada: Reuse, Laboratory (Instructions)
This page intentionallyleft blank-
14
Software Enginc,
0
Uiing Ada: Reuse, Laboratory (Teacher Notes)
UNIT 4: REUSE LABORATORY SPECIFICATION TEACHER NOTES FOR LABORATORY This section must describe to the instructorhow to conduct the laboratory.Topics include: 0 Suggestions on how to make the example seem more realisticby inventing a background tailored to the school in which the course is being taught e Answers to the laboratoryexercises a Additional questions the teacher may want to ask students
0 15
Software Engineering Using Ada: Reuse, Laboratory (Teacher Notes)
This page intentionally left blank.
16
Software Engineering Using Ada: Test
TEST FOR
*SOFTWARE
*
ENGINEERING USING ADA COURSE
1.
True/False
Software developers spend the majority of their time writing code.
2.
'lrue/False
The majority of software changes result from the need to enhance the software.
3.
True/False
A programming language can help developers manage change and communication.
4.
True/False
The only information in a package that is visible to other packages is that contained in the package specification, outside the private part.
5.
Abstraction helps developers separate the the
6.
True/False
A developer who builds an Ada package must write both the specification and the body before it is useful to other developers.
7.
True/False
The stepwise refinement design method results in designs that are easy to change.
8.
True/False
The first decisions you make when following the information hiding design method concern the modules in your program.
9.
True/False
Software developers usually find similarities between the programs they are developing and programs they have developed previously.
from
help software developers build packages that other software
10.
Ada developers can reuse.
11.
Describe the purpose of software design.
Software Engineering Using Ada: Test
12.
Using the principles of abstraction and information hiding, design the interface for a module that implements a counter-that is, something another module might use to maintain a count of the number of times some event or situation occurs.
13.
Consider the following specification of a package for searching an array of integers: package IntegerArraySearch is subtype Array-Index is Integer range 1..1000; type Integer-Array is array (Array-Index) of Integer; procedure SearchArray( ArrayToSearch: Nuwiber_OfElements: Element_To_Search_For: ElementFound: Index_If_Found:
in Integer_Array; in ArrayIndex; in Integer; out boolean; out ArrayIndex
end IntegerArraySearch;
Use generics to rewrite this package to be more reusable.
2
Software Engineering Using Ada: Test
TEST FOR
*
SOFTWARE ENGINEERING USING ADA COURSE TEACHER ANSWERS Software developers spend the majority of their time writing code.
1.
Tiueae
2.
[
alse
The majority of software changes result from the need to enhance the software.
3.
[ualse
A programming language can help developers manage change and communication.
alse
The only information in a package that is visible to other packages is that contained in the package specification, outside the private portion.
4.
u
essential information
from
5.
Abstraction helps developers separate the the irrelevantdetails
6.
True/e
A developer who builds an Ada package must write both the specification and the body before it is useful to other developers.
7.
Truc
The stepwise refinement design method results in designs that are easy to change.
IM
8.
ualse
The first decisions you make when following the information hiding design method concern the modules in your program.
9.
lu/alse
Software developers usually find similarities between the programs they are developing and programs they have developed previously. help software developers build packages that other software
10.
Ada generics developers can reuse.
11.
Describe the purpose of software design. Software design lets software developers decompose aproblem into a set of modules. Each of these modules is simpler than the whole. This is necessaryto reduce the complexity of the overall system, making it easy for individualsto understandportionsof a system. Another reasonfor software design is to break a problem into partsthat can be assignedto a set of individuals. In other words, software design is necessary for large programs to ensure that each person on a team has a coherent development assignment.
-0
Software Engineering Using Ada: Test
12.
Using the principles of abstraction and information hiding, design the interface for a module that implements a counter-that is, something another module might use to maintain a count of the number of times some event or situation occurs.
The followingpackage specificationprovides otherpackages the ability to initializethe count to 0, to increment the count,and to determine its currentvalue. Thisis the essence of counting. package Counter in procedure Set_ToZero; procedure Increment; function Current_Value return Integer; and Counter;
13.
Consider the following specification of a package for searching an array of integers: package IntegerArraySearch is subtype Array.Index is Integer range 1..1000; type Integer_-Array is array (ArrayIndex) oe Integer; procedure Search-Array( Array...To_Search: Number_Of_Elements: Element_To_SearchFor: Element-pound: Index_If_Found:
in IntegerArray; in ArrayIndex; in Integer; out boolean; out ArrayIndex
end IntegerArraySearch;
Use generics to rewrite this package to be more reusable. You can make the array's base data type and index generic. Note the name change for the second parameter.The old name was based on an ordinal counting system. In the generic version, the array's lower bound might not be 1. grenerjL .
type type package type
Item in private; ArrayIndex is range ; Array-Search is Generic_Array is array (Array-index) of Item;
procedure SearchArray( ArrayTo_Search: LastElement: ElementToSearch_For: Element-Found: Index_If_1ound: end ArraySearch;
4
in Generic_Array; in Array_Index; in Item; out boolean; out ArrayIndex
FOR
Software
Engincering
Using Ada:
Survey
SURVEY SOF7,W,4RE ENGINEERING USING ADA COURSE Please answer the following questions. The organization that developed the course material will use this information to improve the course. 1.
Do you feel that you understand basic software engineering principles (abstraction, information hiding, and reuse) after taking this course?
2.
Do you see value in these principles? Why or why not?
3.
Do you see value in using a programming language such as Ada that helps you express these principles? Why or why not?
4.
Would you like to learn more?
Software Engineering Using Ada: Survey
5.
What activity(ies) or example(s) was most helpful to you in understanding the basic software engineering principles?
6.
Do you have any other suggestions for how the course can be improved?
2€
I
Software Engineering Using Ada: Survey
*
SURVEY FOR SOFTWARE ENGINEERING USING ADA COURSE TEACHER ANSWERS There are no right or wrong answers on this section. A suggestion for this survey would be to hand it to the students after they have completed the test and give them extra credit if they fill it out and hand. it in the next day.
3
Software Engineering Using Ada: Survey
This page intentionallyleft blank
44 4
Software Engineering Using Ada Course: Laboratory For Unit 3 SPC-95013-CMC
*
Version 01.00.02
April 1995
Produced by the SOFTWARE PRODUCTIVITY CONSORTIUM SERVICES CORPORATION t.L dcr contract to the VIRGINIA CENTER OF EXCELLENCE FOR SOFTWARE REUSE AND TECHNOLOGY TRANSFER SPC Building 2214 Rork Ifill Road Herndon, Virginia 22070 Copvright © 199k, Software 1 roductivity Consortium Services Corporation, Herndon, Virginia. Permission to tr, copy, modify, and distribute this material for any purpose and without fec is hereby granted consistent with 48 CFR 227 and 252, and provided that the above copyright notice appears in all copies and that both this copyright notice and this permission notice appear in supporting documentation. This material is based in part upon work :ponsored by the Advanced Research Projects Agency under Grant #MDAL972-92-J-1018. The content does not necessarily reflect the position or the policy of the U. S. Goverrnent, and no official endorsement should be inferred. The name Software Productivity Consortium shall not be used in advertising or publicity pertaining to this material or otherwise without the prior written permission of Software Productivity Consortium, inc. SOFTWVARE PRODUCIVITY CONSORTIUM, INC. AND SOFJTWARE PRODUCTIVITY CONSORTIUM SERVICES CORPORATION MAKE NO REPRESENTATIONS OR WARARANTIES ABOUT THE SUITABILITY OF THIS MATERIAL FOR ANY PURPOSE OR ABOUT ANY OTHER MATTER, AND THIS MATERIAL IS PROVIDED WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
PRIEFACE This laboratory and teacher notes are part of the Software Engineering Using Ada Course (SPC-94094 0MG, version 01.00.05) produced by the Virginia Center of Excellence for Software Re use and Technology Transfer. The course, which is a short course aimed at high school students, consists of four units: software engineering, abstraction, information hiding, and software reuse. The laboratory described in this write-up should be performed at the end of the information hiding unit (Unit 3), preferably after the students have completed Homework Assignment 2 of Unit 3. Assignment 2 deals with concepts of the software that students will use in the laboratory and, therefore, serves as a good introduction to the laboratory material.
Preface
This page intentionally left blank.
iv
Softwarc Engineering Using Ada: Unit 3, Information Hiding, Laboratory
*
UNIT 3: INFORMATION HiDING LABORATORY In this laboratory, you will compile and execute an implementation of the rational number package from Homework Assignment 2 in Unit 3. The software you will use is in three files:
"
RATNUM. ADA,
"*
RATNUM_B. ADA,
"•
which contains the procedure ReadSumAndPrintRationalNumbers. This procedure uses the rational number package to read, sum, and print two rational numbers.
which contains the package specification for rational numbers. which contains the package body for rational numbers.
READ_SUM.ADA,
You must first compile the software. Perform the following steps: 1.
.
Create a directory called RATNUM on your C drive: C:> md ratnum
2.
Change your directory to RATNUM: C:> cd ratnum
3.
Copy the software to your current directory. Your teacher will provide you with the location of the software. For example, if it is located in S:\ADA\RATNUM, you would execute the following command: C:\RATNUM> copy s:\ada\ratnum\*.ada
4.
Compile the software. You must first compile the rational number package specification, then the rational number package body, then the Read_SumAndPrintRationalNumbers procedure: C:\RATNUM> janus ratnum.ada C:\\RATNUM> janus ratnum_b.ada C:\RATNUM> janus readsum.ada
You must type the .ADA file name suffix.
.
The Ada compiler will print diagnostic information as it compiles each file. This information, not shown here, should indicate that compilation is progressing without errors. If you see any eiror messages, contact your teacher, 5.
Link the software: C:\RATNUM>
jlink
readsum
Software Engineering Using Ada: Unit 3, Information Hiding, Laboratory
Do not type a file name suffix. After you successfully complete these steps, there will be an executable file called READSUM.COM in your directory. You may now execute the software: C:\RATNUM>
readsum
You will be prompted to enter two rational numbers. You will be asked for the first number's numerator, then its denominator, then the second number's numerator, and finally the second number's denominator. Enter each number as an integer. For instance, the following shows how to instruct the program to compute 1/7 + 3/5: C:\RATNUM> readsum Enter the numerator for the first
number: 1
Enter the denominator for the first number: 7 Enter the numerator for the second number: 3
Enter the denominator for the second number: 5 The sum is 26/35 EXERCISES
1.
Use the software to compute 3/18 - 10/7.
2.
Try using the software to compute 1/1000 + 1000/1. a. Why do you think the software fails? (Hint: Examine the Add function to discover how two rational numbers are added.) b. The lectures on abstraction and information hiding covered the need to express a module's functionality in a package specification. Based on this laboratory, what else do you think must be in a package specification?
2
Software Engineering Using Ada: Unit 3, Information Hiding, Teacher Notes for Laboratory
UNIT 3: INFORMATION HIDING
*
TEACHER NOTES FOR LABORATORY NoTE: This course contains a simplified version of a planned software laboratory. A more elaborate version may be available at a later date. You should have received, along with these instructions, a floppy diskette containing the software solving Homework Assignment 2 in Unit 3. This software is almost identical to that shown in the Unit 3 Teacher Notes, with the following exceptions: "* The software on the floppy diskette includes some error-handling code that lets the compiled program terminate gracefully under abnormal conditions. "* The software on the floppy diskette uses a friendlier input paradigm.
.
The floppy diskette includes the three files of Ada source code discussed in the laboratory write-up: RATNUM. ADA, RATNUM_B. ADA, and READ-SUM. ADA. You must provide each student with a copy of these files. If your computers are linked together on a network and have access to a central file server, you can place them on that server. Each student can then copy the files directly froi-a that server to her or his own computer, as shown in the laboratory write-up. You can also provide each student with a floppy diskette containing the source files and ask them to copy the files from that diskette to their hard drive. Each student must be able to use an Ada compiler. The instructions in the laboratory write-up use the Janus/Ada compiler from R&R Software, Inc. See the file README.TXT on the floppy diskette for more information on using this compiler. EXERCISES
1.
Use the software to compute 3/18 - 10/7. This simple exercise en.'ures that students know how to use the program they have just compiled. Be sure they enter the input values correctly: only integers are accepted.Entering anything else will cause the program to stop prematurely.
2.
Try using the software to compute 1/1000 + 1000/1.
a. Why do you think the software fails? (Hint: Examine the Add function to discover how two rational numbers are added.) The Add function uses the following formula to add two rationalnumbers R1 and R2: R.Numerator
:= R1.Numerator * R2.Denominator + R2.Numerator * Ri.Denominator; R.Denominator := Rl.denorninator * R2.denominator;
Evaluatingthe first assignmentstatement using 1/1000 and 1000/1 yields:
3
Software Engincering Using Ada: Unit 3, Information Hiding, Teacher Noics for Laboratory
I x 1 + 1000 x 1000
I + 1000000 1
An examination of the representationof a rationalnumber in the package specification reveals that Numeratorand Denominatorare values of type Integer.An Integer value can range from -32,768 to 32,767. Since 1,000,000 is greater than 32,767, evaluating the expression causes an overflow. The Ada language requires that a compilergenerate code to detect these conditions. This is an instance of language standardization,discussed in Unit 1. b. The lectures on abstraction and information hiding covered the need to express a module's functionality in a package specification. Based on this laboratory, what else do you think must be in a package specification? The package specifications shown include informution on the procedures and functions, andhow to use them. The specificationsshould also show the ways in which theprocedures andftnctions can fail!
4