Table Of ContentProgram Development by Stepwise Refinement
and Related Topics
By N. GEHANT
(onuccit recive Seotanber 22, 1980)
Computer program development ly stepwise refinement hae been
voor! by many people. Wa take anather look at stepwise refine.
‘ent in light of recent developments in programming layne and
prowramming methodology such as abstract data pes, correctness
[proofeand format apecifications,parolle programs ana! multiversion
programs. We offer suggestions for the refinement processand discuss
program maintainability,
“The cormect design of nontivil programs and systems of programs
is an intellecrullychallenying snd dificult task. Often programa are
designed with very litle tine spent on the design itself, the effort,
‘being concentrate} on coding. ‘Thi could be due to management's
desire vo ace womething working as soon aa possible to bo assured that
‘work is progressing, or it could be due tothe programmer’ dcsirv to
“adtack the prabler right as
"Not only there no exaphasis on design, the wpprowch Lo i ia also
not ayatematie or disciplined, This resules in programs thet do aot
tet epecifeationsin wrmsof corte output and performance require
ments,
‘What we want is a programming methodology chat pls some
isciplne and wirucurein the design process without stilling creativiy
‘A progeucaming methodology shoul:
(i) Hp ws marcer the corplesty of the problra being solved and
vet anne guidelines on how to ormuite the problem elution.
Tai Provide us with writen record of the design proce, The
erign can lien be teed by others, and the design dovkiona can he
‘appreciate or constructively eriticized,
(ai) Result im programa that are uniertandable.
oar
(io) Lesd to programs whose corectnesa can be verified by prook
Since proofs are difficult, the methodology should allow for a sy
tematic approach vo progear lasting
(Gi) Be generally applicable and sol restricted tow clas of problems,
(Gi) Allow forthe production of efficient programs.
(oii) Allow far the production of prosrams that can he modified
systematically.
In this tutorial wo discuss « programming methodology called step
‘wis refinement and informally show that it salisfios these criceria
I. STEPWISE REFINEMENT
Stepwise refinement is a top-down design approsch to program
development (first advocated hy Wirth’), Wirth really gave a aye
temacie formulation and description of what many programmers were
roviously doing intuitively. According to Brooks, stopeice refinement
{s the oo: important new programming formalization of the decade
Stepwise refinement ic wpplicable not only to program desien hut also
to the desig of complex eyatems
In a top-down approsch, the problem to be solved is decomposed or
zofinod into subproblems which ure then solved, The decomposition or
Feflnemsent swat he auch tha"
(2) "The subproblems should he solvable
(i) A subproblem should be solvable wich aa itl impact on the
other subproblems as posible
(ii) The solution of eueh subproblem should involve less effort than
he original problem,
1G) Onoe the subprobleme are solved, the solution ofthe problem
hhould not require mich aditona efor.
"This prvessisrepeated on the subproblems; of course ifthe slusion
‘of « problem is obvious or trivial, then thie decomposition is not
1f-P> is cho inital problem formulation/soluton, thu dhe fal
problem formulation/solution P, fan executable program) is arrived
at aftr acerios of gradual "Yofinement” steps,
Pom Pio Ppa Pa
‘The refinement Ps of Ps produced by supplying more details for
the problem formblation/solution Ty. The reGnements. Pay, Py
‘epresent different levels of sbemaction, Py may be said give the
rest abstract view ofthe problem solution P., while # reprecena
‘otal version of the setion for By
‘As an example of abstraction evel, considera program that auto-
‘mates the record-keeping of an ineurance company. AL the highest
level of abetraction, the program deal withthe insurance company at
aout, At aueeceding lower levee of absteection che program dents
vit
+ itferent snaurance enters (nats, heme, He 6)
* groupe of polices in the sve eategorie
1 Titividual polis in the ave rors
derail of individual polices
Fach refinement consiss uf w sequence of instructions and data
Aeserptions By,
Pa
Po
In each rofinement stap, we provide mare details on how each Pyis ta
be implemented, The refinement process stops when we reuch a stage
{G) hore all the instructions can be exceuted on a computer, oF
(ir) where instruction can be eesily Irate 1 eomputersezeut
sb: nstruetions
Pictorial, the refinement process may be depicted us shoven in
Fig. 1 The foal program ‘a collection of the covles x the lst
refivemat evel Pe
‘The design ean be probed y wy esr level of detail # (= =m).
Undeminding the design process ie wed by Une fact thac level #
provides overview of vale ¢ + 1 theo
"We iltzave the seyoriae refinement proceas wich annotate ex
amples, The ruins we wil use Zor conveying our iden wil be
Dsl He? nd inluse guste commande "Pr wil he used to show
te executable version uf some proqrara,
|
“lo Lele Es
cre H
gt These
SIEOWISE REFINEMENT PROGRAM DEVELOPMENT 349
The guarded commands are
(i) Selection
te = su
Ub Su
I = st,
‘The Bs ace calle the yards (Boolean expressions) an the 8 ane
staremene lim, Fora macceaaful execucon ofthe selection statement,
srleast one of the guards mus be true. I only one guar i (rue, then
the corresponding statement list i exceuted, I moze thon one guard
Je true, then ore of thy corresponding statetnl Use iy sleeved
ondeterministielly (iy Ue te earn el beforehand) anu es
ted,
fa — thon both the guards are cue and either of che stavements
max 12 @ ur mae '= D may hee executed. Rther way, the answer i
Hight. This symnelry i aesthelivaly pleasing: when! compared 48
‘conventional deterministic programing.
ie) Repetitine
‘The loop ie repeatedly exceated ws Tung ws one ofthe guards i true
fone guned ix i, ths the corresponding seine! T x ee
Asin che wlection aterm, i unre tat one guard i true, he ne
‘ofthe corresponding lar is erbtrariy elected and executed.
Imaplemestatn if three tars i € Pascal Py yl be
deerminite, For example, in 01/1
fey Selection
rb,
THEN 00; SL; END:
ELSE IF 0; THEN DO; SL;; END;
ELSE IF 6, THEN DO; SL,: END:
ELSE ERROH
250 THE BELL SYSTEM TECIINICAL JOURNAL, MARCH 196:
Fb.
ELBE IF by THEN DO; SL, END:
ELSE If iy THEN D0; SL; END:
ELSE GOTO LE:
ENDL
le:
ote: hess aatemenis could be mare convenietly ismplemuntel
SLLKCT aed RAVE seatemonts
ving che near mL
1M, EXAMPLES OF STEPWISE REFINEMENT
‘The raompes une to Wusteao slepwite rfinemanc are amall out of
necenriy, ‘The redor i cnontaged to ppl stepwise renew 1
larger problems.
exemple 1
\Weily w program to simelate a wock in Tube’ ie
Anil refinement Py
‘Simulates week in John's it
we were programming in 4 Tinjonge that underaceod the shove
inetraction, then we woulda’ have to rine turer
Refinoment »
dis manday [nant day bo ve Smulated iso)
be repeat
© simulate day din Joha's tte
& Unb week over
[A tetinemene cunsie-s of programming language mstractions mixed
ith nglsh statements
Refinement Pe
Linge of Pia rfined us
Sloep unt alain goes off
Go threugh morning rtusl
Spend tne ay
530 though evening etal
Prapare to lao
Line dia etd we
SSIEPWSE REFINEMENT PROGRAN UEVELOPNENT 351
d= sundey 0
He? sunday
monday
Succi)
‘hora the Poscel fanetion SUCC gives the nest dav in the range of
rs mona ny, == unde, Th: eek aver” fined As
“d= nl
(Collecting checeretinemanra of #5 instructions, we get refinement
z
(t= monday
repeat
‘Sleep until alarm gost off
Go through marnina ritual
Spena the say
Prone to logo
WG nday + d= wanday
Tay sunday = a succia)
#
untit d = monday.
‘This collection can be done mochanially and we shall m general omit
1 Spend the day" may he refined 38
We weekeay > go tn wore
rete home
weekend > read newpaper
laze arount
reat! bce
watch TV
"
Similay, che acer inatvetions of Fe may be refined and the
refinement process eontinaed to the derived lavel of detail. Tn the
refinement wo have tried to model procetses of the problem domain.”
An nitiel decomposition might not be feasible a nice in which cane
sve bock up and try another decomposcon, We all only present the
final 26 of decompositions,
Example 2
‘Write & prosrum chat ronds in a let of positive mumbers 0,
ae (2-2 0) nl pri the suet of al aural numbers up to each
fa ky the ums
Se Ba, Be
962 THF BELL SYSTEM TECHNICAL JOURNAL, MARCH 1081
Initial vefinement Py: Print Ea E24 =
Pr
read.a
‘do while there .
exists data —+ Compute sum = 3 i
Print eum
od
ecauce we are aiming for an executable program in 2 roquencial
programming langue, the refinement P, reflects the decision to reed
In on injut latent, compare ies som, pint the sum, and then Yead
fother inpur element. Allernarls, had our target been a parallel
fomputer we would hive prolibly read in all the input elements,
Computed the sma in parallel, and then printed them out. Many
Implicit decisions underlie weery refinement.
Be: while there exit date
1 refined to
not EOF
+ Conte sum = Sie
is rofined to
rumi= 0 (@um=O= 1424-41)
dolea + ia i+tiaum'= sum + fod
Lotus wow examine the coneep! of loop invaiant. A loop invariant
‘an astertion about program varibles; it statically espuures the
resning of oop thus helping ur understand it. Loop invariants are
fron belone and after the exetion na loop, and before and after each
tecution of the Toop body. Dijknira" auggerts some ways of finding
the loop invariant using the dased poet-condition (sate of variables
lfter the lonp terminates) The Toop invariant an actually aid im
determining the guards and the corresponding statement lit.
“Let be the loop invaranl sa = 4 1+ 2+ woe Lis true
initlly ecause {= O nd sum = Fealoation ofthe guard i # a does
ro floc fs the statement i= i+ | destroys J, reulting in eum — 0
PUL O41 1 Bat som ~ sum + f restores the validity of
invariant. When the guatd evaluates 19 fale, ie, = he lop
terminates, Now in addition to J eing true we have f= a, smplying
Ghevdesved remit sum = 0+ 742-4 ba
How can we demonstrat loyp termination? Kor thie we must show
the existence ofa fanction, initially =O, whe valoo is deeremed by
Tn we te ed teens in et dn ancl
you get ins rn en Tana nh ce
STEPWISE MREFINEMENT PROGRAM DEVELOPMENT 353,
cone every time the loop ic executed. When this funetion hecomes = 0,
tre stop. Such a function is a ~ t; executing ("= 4-+ 1 decreases ice
value by 1. When «'~ 1 ~ 0, we have 1 = a which is when the guerd
tevaluaies to flee and the loop erminate.
Continuing the refinements we get
by
road .
conotcor + {eompaesum~ 5 i}
feo
sum foum=041424-0 40
deira > imrtt
od
Prin um
od
Patino
SUM: PROG OPTIONS(MAIN
DCL A /*NEXT INPUT ELEMENT */
1 /*L00P VARIABLE */
[SUM /*SUM=OVT Hb 0
Jerxe0 EC,
EOF BITCID NTC OB
ON ENDPILE EOP"
GET UsTiAy
DO WHILE (-EoFY:
mo; SuM=o
DO WHILE U~—Ay
fet: SUNS=-SUNK I END;
PUT SKIPLIST C SUM UPTO. A,“18 SUM:
Ger Listy
END:
END SUM:
Bampie3
Visite a program to detormine the maximum element value of an
xmamay A (mn =
Be: datermine the mae element value o A
i: 20 (last row examines,
inilaze max. max is the maximum olement
fof rowa t+ Fp invariant)
954 THE BELL SYSTEM TECHNICAL JOURNAL, MARCH 1061
doaliows + Rint
fot examined marc rmaximemgrous, max)
oa
Pe: © initlize max a refined to
max = ATT, 17
all rows not examined
Is refined to
inn
fax #= anlar (ow J, max)
isretined as
FO" (max = maximum ot rows 1...) 1 and elements
1 jaf row -looa invariant ey)
doll alemaigol yom) tt
row inot examined max:= MAXmax, Als!)
od
Tein the loop invariant. As an exercise, the reader should try and show
‘hat the loops leave fy and Ze invariant, i, unchanged
"Pa «al cements of rom j noe examined
fs refined a6
jen
imax = MAXimax, Ali jD
is refined as
W max Ali j] + skip
qkimensai a) + meen all
‘where skip dno the null statement.
“The iterative feature inthe most important feature ofa progamming
language.’ The do --- od consirac allows us to express algorithms
clearly and suceinety. The above example could have been done bere
‘ha the author nol wel th do --- od constmic Lo jut simulate the
while statement, Malking fuller see uf the do --- od construct, we get
the following program forthe aoe problem
Ph: j=. {number of rows examined eo far}
j= 0 [number ofelemants of row i+ 1 examined go far)
Inalies max (mas te maxim of al the elements in th first
‘rows and the fal olements of row + 1} ~7
ao i<mrowsandjen tae t
flomontsof row i= 4 maxi= MAXImax, Al.)
examined
Upc rows and al» move tothe next raw
‘element of row i+ 1
examined
od
SIEPWISE REFINEMENT PROGRAM DEVELOPMENT 958,
jo
max = ALT, 1] (maxis the maximum ofall the
elements inthe fat /eows
and the st elements of raw i + 1) —
do jemandicnnn fied
‘max = MAxemex, Af, JD
[emendj-a + init tj
od
Gries aso shows that the do -- od construct urualy eliminates the
‘need for loop exits necessary in programs that use the while stave-
Example &
"The Touch-Tone®cslephone provides an easy but limited meana of
communicating with a computer (see Fig 2). The problem isto write
f program that provides a simple adding machine to the user” For
example:
User offhonk 1 # 52 #65 onhook
input:
system one" “i ten
response: peint pine
eco} feo” een”
"The charneters # ond « roprosont + and =, respectively,
“The following modules are avaiable o the programmer
© SPEAK string)—provides an mui response for the number
represented hy the sting
aoe
256 THE BELL SYSTEM TECHNICAL JOURNAL, MARCH 1901