348
OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING LANGUAGE OLE L EHRMANN MADSEN Aarhus University B IRGER MØLLER -P EDERSEN Ericsson Research, Applied Research Center, Oslo KRISTEN NYGAARD University of Oslo Copyright c 1993 by Ole Lehrmann Madsen, Birger Møller-Pedersen, and Kristen Nygaard. All rights reserved. No part of this book may be copied or distributed without the prior written permission of the authors

OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

OBJECT-ORIENTEDPROGRAMMING

INTHE BETA PROGRAMMING

LANGUAGE

OLE LEHRMANN MADSEN

AarhusUniversity

BIRGER MØLLER-PEDERSEN

EricssonResearch, AppliedResearch Center, Oslo

KRISTEN NYGAARD

University of Oslo

Copyright c�

1993by Ole LehrmannMadsen,BirgerMøller-Pedersen,andKristenNygaard.All rightsreserved.No partof thisbookmaybecopiedordistributedwithout theprior written permissionof theauthors

Page 2: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Preface

This is a book on object-orientedprogrammingandtheBETA programminglanguage.Object-orientedprogrammingoriginatedwith theSimulalanguagesdevelopedat theNorwegianComputingCenter, Oslo, in the1960s.ThefirstSimulalanguage,SimulaI, wasintendedfor writing simulationprograms.Si-mula I waslaterusedasa basisfor defininga generalpurposeprogramminglanguage,Simula67. In additionto beinga programminglanguage,Simula1

wasalsodesignedasa languagefor describingandcommunicatingaboutsys-temsin general. Simulahasbeenusedby a relatively small communityformany years,althoughit hashada major impacton researchin computersci-ence.Therealbreakthroughfor object-orientedprogrammingcamewith thedevelopmentof Smalltalk. Sincethen,a large numberof programminglan-guagesbasedon Simulaconceptshave appeared.C++ is the languagethathashadthe greatestinfluenceon the useof object-orientedprogramminginindustry. Object-orientedprogramminghasalsobeenthesubjectof intensiveresearch,resultingin a largenumberof importantcontributions.

Theauthorsof this book,togetherwith BentBruunKristensen,have beeninvolvedin theBETA projectsince1975,theaim of which is to developcon-cepts,constructsandtoolsfor programming.TheBETA languageis onemainresultof thisproject,thevariousstagesof whichhavebeendescribedin manydifferentreportsandarticles(Kristensenetal., 1976;1983a,b;1985;1987a,b;1988; Madsen,1987; Madsenand Møller-Pedersen,1988; 1989a,b;1992;Madsenet al., 1983).This bookcontainsadescriptionof theBETA languagetogetherwith theconceptualframework on whichBETA hasbeenbased.

The Mjølner2 BETA Systemis a programmingenvironmentsupportingobject-orientedprogrammingin BETA. TheMjølner BETA Systemhasbeendevelopedby the Mjølner project (Dahleet al., 1986; Knudsenetal., 1992),which wasa cooperative Nordic projectwith participantsfrom Sweden,Nor-way, FinlandandDenmark. The Mjølner BETA Systemincludesan imple-mentationof BETA and a large numberof libraries and applicationframe-works. It alsoincludesaHyperStructureEditorandanobject-orientedCASE

1Simula67 waslaterrenamedto just Simula, which is usedin this book.2The nameMjølner is taken from Nordic mythology, whereMjølner is the nameof the

godThor’shammer. Accordingto mythology, this hammeris theperfecttool thatcannotfail,growswith thetask,andalwayscomesbackto Thor’shand.

v

Page 3: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

vi PREFACE

tool for supportingdesignusingBETA. Thesystemis a commercialproductmarketedby Mjølner InformaticsA/S. AppendixB containsa moredetaileddescriptionof theMjølnerBETA System.ReadersshouldconsulttheMjølnermanualsfor further detailsbefore trying to run the examplesin this book.TheMjølner BETA Systemis currentlyavailablefor theMacintosh,andfor anumberof UNIX-basedworkstationsrunnningX-Window Systems.

Draft versionsof this bookandpre-releasesof theMjølner BETA Systemhave beenusedfor teachingobject-orientedprogrammingat the Departmentof InformationandMediaSciences(IMV) andtheComputerScienceDepart-ment(DAIMI), bothatAarhusUniversity. At IMV, BETA is usedfor introduc-tory programmingandatDAIMI it is usedasasecondyearcoursein program-ming languages.They have alsobeenusedfor teachingat a numberof otherplaces,including theUniversitiesof Copenhagen,Oslo,BergenandOdense.Draft versionshave alsobeenusedfor BETA tutorialsgivenat theOOPSLA’89, ’90 and’91 conferences(Object-OrientedProgramming,Languages,Sys-temandApplications),at theTOOLS’91 and’92 conferences(TechnologyofObject-OrientedLanguagesandSystems),andat EastEurOOPe’91 (EastEu-ropeanConferenceon Object-OrientedProgramming).

The book is organizedasfollows: Chapters1 and2 introducethe basicconceptsof object-orientedprogramming;Chapters3–12area descriptionofsubjectssuchasobjects,patterns,sequentialexecution,the virtual concept,block structureand proceduralprogramming. The multi-sequentialaspectsof BETA, including coroutinesand concurrency, are describedin Chapters13–15. Chapter16 dealswith exceptionhandling,Chapter17 describesthemodularizationof large programs,and Chapter18 presentsthe conceptualframework underlyingBETA. AppendixA includesagrammarfor BETA, andAppendixB givesadescriptionof theMjølner BETA System.

Whenreadingthebook, therearethreemainsubjectareasthatshouldbecoveredat thesametime:

� TheBETA language,Chapters3–16

� Modularization,Chapter17

� Theconceptualframework, Chapters2 and18.

It is recommendedthatreadersstartwith Chapters1–6;Chapter2 introducespartof theconceptualframework, andChapters3–6introducepartof BETA.

Chapter18, the main chapteron the conceptualframework, may thenbereadbeforereadingChapters7–16. Dependingon the reader’s previous ex-perience,it may be difficult to graspChapter18 on a first reading,so it isrecommendedthat this is readagainafter having readthe book’s remainingchapters.In a teachingsituationit is recommendedthat theconceptsdetailedin Chapter18arediscussedwhile readingtheremainingchaptersof thebook.

Page 4: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

PREFACE vii

Chapter17,onmodularization,maybereadafterChapters3–6.In ateach-ing situationit is recommendedthat it is readassoonasthestudentshave towrite otherthanjust trivial programs.Experienceshows that,from thebegin-ning, studentsshouldbe trainedin splitting a programinto convenientmod-ules,includingtheseparationof interfaceandimplementation.

Acknowledgements

The BETA projectwasinitiated in 1976aspart of what wasthencalledTheJoint Language Project. Peoplefrom The Regional ComputingCenterandComputerScienceDepartmentat AarhusUniversity, the Institute for Elec-tronic Systemsat Aalborg UniversityCentre,andtheNorwegianComputingCenter, Oslo participatedin that project. The initiative for the project wastaken in theautumnof 1975by BjarnerSvejgaard,Directorof TheRegionalComputingCenter.

The BETA languagewas developedby the authorstogetherwith BentBruun Kristensen.In addition,a large numberof peoplehave beeninvolvedin the developmentof BETA andthe Mjølner BETA System,including col-leaguesandstudentsatAarhusUniversity, TheNorwegianComputingCenter,Oslo University, Aalborg University, andMjølner Informatics. In particular,thecontributionsof DagBelsnesandJørgenLindskov Knudsenareacknowl-edged.

Developmentof theMjølner BETA Systemin theNordic Mjølner projecthasbeensupportedby TheNordicFundfor TechnologyandResearch.Partic-ipantsin theMjølner Projectcomefrom Lund University, Telesoft,EB Tech-nology, TheNorwegianComputingCenter, Telenokia,SyswareApS,AalborgUniversity and AarhusUniversity. The main implementorsof the MjølnerBETA SystemarePeterAndersen,LarsBak, JørgenLindskov Knudsen,OleLehrmannMadsen,Kim JensenMøller, ClausNørgaard,andElmerSandvad.In addition,Karen Borup, SørenBrandt, JørgenNørgaard,ClausH. Peder-sen,TommyThorn,PerFackSørensenandPeterØrbækhave participatedinvariouspartsof theimplementation.

The development of the Mjølner BETA System has been supportedthrougha contractwith Apple ComputerEurope,Paris. We are grateful toLarry Taylor for the greatsupporthe hasprovided for BETA. Developmentof the systemhasalsobeensupportedby a contractwith Apollo Computer,Finland,andby thedonationof workstationsfrom Hewlett-Packard.

Thedevelopmentof BETA andtheMjølner BETA Systemhasbeensup-portedby theDanishNaturalScienceResearchCouncil,grant. no. 11-3106,FTU 5.17.5.1.25,theDanishNaturalResearchCouncil, grant. no. 11-8285,theDanishResearchProgrammefor Informatics,grantnos. 5.26.18.29.(theDevise Project),The Royal Norwegian Council for ScientificandIndustrialResearch,grantno. ED 0223.16641(theScalaproject),andthroughtheEuro-

Page 5: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

viii PREFACE

peanCommission’sEspritEuroCoOp(5303)andEuroCODE(6155)projects.We would like to thankcolleaguesandstudentsfor valuablecomments,

inspiringcriticisms,andthediscoveryof errorsin preliminaryversionsof thisbook.Kim Halskov MadsenandRandellTrigg deservespecialthanksfor theiruseof preliminaryversionsof thebook in teachingat IMV; their experienceandcommentshave hada large influence.Otherusefulcommentshave beenprovidedby BirgerAndersen,PeterAndersen,LarsBak,LoneFaber, CarstenHansen,Dag Helstad,AnetteHviid, JørgenLindskov Knudsen,Kim JensenMøller, ElmerSandvad,AlexandreValenteSousa,Kristine StougaardThom-sen,andthemany studentswhohavebeenexposedto previousversionsof thebook.

Wewould like to thankPeterWegnerfor hisusefulcommentsandencour-agementto write thisbookandSimonPlumtreeof Addison-Wesley for hispa-tience.During thepreparationof themanuscriptwe receivedgreathelpfromSusanneBrøndberg, KarenKjær Møller andtheproductionstaff at Addison-Wesley.

Theauthorswould like to thanktheir families(Ole: Marianne,Christian,Anne Sofie; Birger: Kirsten, Kamilla, Kristine; Kristen: Johannaand to amoderateextent childrenandgrandchildren).The BETA projectwould nothavebeenthesameandthisbookwouldnothavecomeinto existencewithouttheirpatienceandunderstanding,andwithouttheirparticipationin many livelygatherings3 throughouttheyears.

Ole LehrmannMadsenBirgerMøller-Pedersen

KristenNygaard

May 1993

3We alsothankthewhitewineproducersin Germany, France,Italy andCalifornia.

Page 6: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Contents

Preface v

1 Intr oduction 11.1 Benefitsof object-orientation. . . . . . . . . . . . . . . . . . 11.2 Object-orientedprogrammingandBETA . . . . . . . . . . . . 31.3 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2 Intr oduction to BasicConcepts 112.1 Perspectiveson programming. . . . . . . . . . . . . . . . . . 12

2.1.1 Proceduralprogramming. . . . . . . . . . . . . . . . 122.1.2 Functionalandconstraintprogramming . . . . . . . . 14

2.2 Object-orientedprogramming . . . . . . . . . . . . . . . . . 162.2.1 Manualsystems. . . . . . . . . . . . . . . . . . . . . 162.2.2 Computerizedphysicalmodels. . . . . . . . . . . . . 17

2.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222.4 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

3 Objectsand Patterns 233.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

3.1.1 Summary . . . . . . . . . . . . . . . . . . . . . . . . 273.2 Referenceattributes . . . . . . . . . . . . . . . . . . . . . . . 31

3.2.1 Staticreferences . . . . . . . . . . . . . . . . . . . . 313.2.2 Dynamicreferences . . . . . . . . . . . . . . . . . . 323.2.3 Dynamicgenerationof objects . . . . . . . . . . . . . 333.2.4 Exampleof usingdynamicreferences. . . . . . . . . 343.2.5 Qualifiedreferencesandremoteaccess . . . . . . . . 35

3.3 Patternattributes . . . . . . . . . . . . . . . . . . . . . . . . 363.3.1 Self-reference. . . . . . . . . . . . . . . . . . . . . . 393.3.2 Procedure,functionandclasspatterns. . . . . . . . . 393.3.3 Basicpatterns. . . . . . . . . . . . . . . . . . . . . . 42

3.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443.5 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

ix

Page 7: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

x CONTENTS

4 Repetitions 474.1 Reallocation,assignmentandslice . . . . . . . . . . . . . . . 494.2 Thetext pattern . . . . . . . . . . . . . . . . . . . . . . . . . 514.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524.4 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

5 Imperati ves 535.1 Introductionto evaluations . . . . . . . . . . . . . . . . . . . 535.2 For-imperative . . . . . . . . . . . . . . . . . . . . . . . . . . 555.3 If-imperative . . . . . . . . . . . . . . . . . . . . . . . . . . 565.4 Labelsandjump imperatives . . . . . . . . . . . . . . . . . . 585.5 A largeexample. . . . . . . . . . . . . . . . . . . . . . . . . 595.6 Assignmentandequality . . . . . . . . . . . . . . . . . . . . 59

5.6.1 Equality . . . . . . . . . . . . . . . . . . . . . . . . . 655.6.2 Basicpatterns. . . . . . . . . . . . . . . . . . . . . . 66

5.7 Computedreferencesandcomputedremotename . . . . . . . 665.8 Detaileddescriptionof evaluations . . . . . . . . . . . . . . . 67

5.8.1 Objectevaluation . . . . . . . . . . . . . . . . . . . . 695.8.2 Evaluationlist . . . . . . . . . . . . . . . . . . . . . 705.8.3 Assignmentevaluation . . . . . . . . . . . . . . . . . 715.8.4 Valuerelations . . . . . . . . . . . . . . . . . . . . . 72

5.9 Block structureandscoperules . . . . . . . . . . . . . . . . . 725.10 Objectkindsandconstructionmodes. . . . . . . . . . . . . . 74

5.10.1 Objectkinds . . . . . . . . . . . . . . . . . . . . . . 755.10.2 Constructionmodesandinsertedobjects. . . . . . . . 755.10.3 Summaryof constructionmodes. . . . . . . . . . . . 76

5.11 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785.12 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

6 Sub-patterns 816.1 Specializationby simpleinheritance . . . . . . . . . . . . . . 816.2 Specializationof actions . . . . . . . . . . . . . . . . . . . . 906.3 Enter/exit-partsfor sub-patterns . . . . . . . . . . . . . . . . 956.4 Theobjectpattern. . . . . . . . . . . . . . . . . . . . . . . . 966.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986.6 Qualificationsandscoperules . . . . . . . . . . . . . . . . . 99

6.6.1 Qualification . . . . . . . . . . . . . . . . . . . . . . 996.6.2 Scoperules . . . . . . . . . . . . . . . . . . . . . . . 100

6.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1016.8 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Page 8: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

CONTENTS xi

7 Virtual Procedure Patterns 1057.1 Motivation. . . . . . . . . . . . . . . . . . . . . . . . . . . . 1067.2 Declarationof virtual pattern . . . . . . . . . . . . . . . . . . 1097.3 Direct qualificationof virtual patterns . . . . . . . . . . . . . 1137.4 Continuedextensionof avirtual pattern . . . . . . . . . . . . 1147.5 More examplesof usingvirtual patterns . . . . . . . . . . . . 115

7.5.1 Specializationof initialization patterns. . . . . . . . . 1157.5.2 Computationof salaryfor differentjob types . . . . . 1167.5.3 Geometricfigures. . . . . . . . . . . . . . . . . . . . 1167.5.4 Definingcontrolabstractions. . . . . . . . . . . . . . 1167.5.5 Arithmeticexpressions. . . . . . . . . . . . . . . . . 119

7.6 Benefitsof virtual patterns . . . . . . . . . . . . . . . . . . . 1197.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1217.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1237.9 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

8 Block Structure 1278.1 Simpleblock structure . . . . . . . . . . . . . . . . . . . . . 1278.2 Classgrammar . . . . . . . . . . . . . . . . . . . . . . . . . 1288.3 Flight reservationexample . . . . . . . . . . . . . . . . . . . 1318.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1348.5 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

9 Virtual ClassPatterns 1399.1 Directly qualifiedvirtual classpatterns. . . . . . . . . . . . . 1399.2 Generalparameterizedclasspatterns. . . . . . . . . . . . . . 1419.3 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142

10 Part Objectsand ReferenceAttrib utes 14510.1 Partobjects . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

10.1.1 Independentanddependentparts. . . . . . . . . . . . 14710.2 Referenceattributes . . . . . . . . . . . . . . . . . . . . . . . 14910.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15210.4 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

11 Pattern Variables 15511.1 Declarationof patternvariables. . . . . . . . . . . . . . . . . 15511.2 Example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15811.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15911.4 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

Page 9: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

xii CONTENTS

12 ProceduralProgramming 16312.1 Functionalclasses. . . . . . . . . . . . . . . . . . . . . . . . 16412.2 Higherorderprocedurepatterns . . . . . . . . . . . . . . . . 16912.3 Virtual classesandgenericity . . . . . . . . . . . . . . . . . . 170

12.3.1 Pureobject-orienteddefinitionof classRing . . . . . 17012.3.2 Functionaldefinitionof classRing . . . . . . . . . . . 17212.3.3 Classattributesversustypeattributes . . . . . . . . . 17412.3.4 Moreon extendingvirtual classes . . . . . . . . . . . 175

12.4 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

13 Deterministic Alter nation 17713.1 Executionstacks . . . . . . . . . . . . . . . . . . . . . . . . 180

13.1.1 Languageconstructsfor basiccoroutinesequencing. . 18313.2 Generators. . . . . . . . . . . . . . . . . . . . . . . . . . . . 18713.3 Componentsandrecursiveprocedurepatterns . . . . . . . . . 18713.4 Abstractsuper-patterns . . . . . . . . . . . . . . . . . . . . . 189

13.4.1 Symmetriccoroutines . . . . . . . . . . . . . . . . . 19113.4.2 Quasi-parallelsystems . . . . . . . . . . . . . . . . . 193

13.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19413.6 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197

14 Concurrency 20114.1 Concurrentexecutionof components. . . . . . . . . . . . . . 202

14.1.1 Simplesynchronization. . . . . . . . . . . . . . . . . 20214.2 Monitors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206

14.2.1 Monitor conditions . . . . . . . . . . . . . . . . . . . 20714.3 Direct communicationbetweencomponents. . . . . . . . . . 209

14.3.1 Synchronizedcommunicationbetweencomponents. . 20914.3.2 Portscontrollingseveraloperations . . . . . . . . . . 21114.3.3 Restrictedacceptance. . . . . . . . . . . . . . . . . . 212

14.4 Compoundsystems. . . . . . . . . . . . . . . . . . . . . . . 21514.4.1 Indirectcommunicationbetweeninternalsystems. . . 21614.4.2 Communicationwith internalsystems. . . . . . . . . 217

14.5 Readersandwritersproblem . . . . . . . . . . . . . . . . . . 21814.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22114.7 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

15 Nondeterministic Alter nation 22515.1 Alternatingexecutionof components. . . . . . . . . . . . . . 22615.2 A distributedcalendar. . . . . . . . . . . . . . . . . . . . . . 22815.3 Boundedbuffer . . . . . . . . . . . . . . . . . . . . . . . . . 23115.4 A simplegame . . . . . . . . . . . . . . . . . . . . . . . . . 23215.5 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

Page 10: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

CONTENTS xiii

16 ExceptionHandling 23716.1 Simpleexceptions. . . . . . . . . . . . . . . . . . . . . . . . 23916.2 Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24316.3 Partial recovery . . . . . . . . . . . . . . . . . . . . . . . . . 24416.4 Handlersfor procedurepatterns. . . . . . . . . . . . . . . . . 24416.5 Systemexceptions . . . . . . . . . . . . . . . . . . . . . . . 24616.6 Language-definedexceptions. . . . . . . . . . . . . . . . . . 24916.7 Advanceddesignof exceptionpatterns. . . . . . . . . . . . . 25016.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25316.9 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253

17 Modularization 25517.1 Fragments. . . . . . . . . . . . . . . . . . . . . . . . . . . . 256

17.1.1 Forms . . . . . . . . . . . . . . . . . . . . . . . . . . 25717.1.2 Slots . . . . . . . . . . . . . . . . . . . . . . . . . . 25817.1.3 Fragment-form. . . . . . . . . . . . . . . . . . . . . 25917.1.4 Fragment-group. . . . . . . . . . . . . . . . . . . . . 25917.1.5 Fragmentlibrary . . . . . . . . . . . . . . . . . . . . 26017.1.6 Origin of a fragment-group. . . . . . . . . . . . . . . 26117.1.7 Thebasicenvironment . . . . . . . . . . . . . . . . . 26217.1.8 Include . . . . . . . . . . . . . . . . . . . . . . . . . 26417.1.9 Body . . . . . . . . . . . . . . . . . . . . . . . . . . 265

17.2 Separationof interfaceandimplementation . . . . . . . . . . 26717.2.1 Abstractdatatypes . . . . . . . . . . . . . . . . . . . 271

17.3 Alternative implementations . . . . . . . . . . . . . . . . . . 27417.4 Programvariants . . . . . . . . . . . . . . . . . . . . . . . . 27617.5 Usingseverallibraries . . . . . . . . . . . . . . . . . . . . . 27817.6 Visibility andbindingrules . . . . . . . . . . . . . . . . . . . 27817.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28017.8 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

18 ConceptualFramework 28318.1 Physicalmodeling. . . . . . . . . . . . . . . . . . . . . . . . 28418.2 Informationprocesses. . . . . . . . . . . . . . . . . . . . . . 28718.3 Conceptsandabstraction . . . . . . . . . . . . . . . . . . . . 290

18.3.1 Phenomenaandconcepts. . . . . . . . . . . . . . . . 29018.3.2 Aristotelianview . . . . . . . . . . . . . . . . . . . . 29218.3.3 Prototypicalview . . . . . . . . . . . . . . . . . . . . 29318.3.4 Otherviewsof concepts . . . . . . . . . . . . . . . . 29418.3.5 Representingconceptsin BETA . . . . . . . . . . . . 295

18.4 Theabstractionprocess. . . . . . . . . . . . . . . . . . . . . 29518.5 Classificationandcomposition . . . . . . . . . . . . . . . . . 297

18.5.1 Classification. . . . . . . . . . . . . . . . . . . . . . 297

Page 11: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

xiv CONTENTS

18.5.2 Composition . . . . . . . . . . . . . . . . . . . . . . 30018.6 Relations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30318.7 Representativeelementsof adescription . . . . . . . . . . . . 30418.8 Graphicalnotation . . . . . . . . . . . . . . . . . . . . . . . 30718.9 Elementsof amethod. . . . . . . . . . . . . . . . . . . . . . 308

18.9.1 Generalapproach. . . . . . . . . . . . . . . . . . . . 30918.9.2 Analysis . . . . . . . . . . . . . . . . . . . . . . . . 31018.9.3 Design . . . . . . . . . . . . . . . . . . . . . . . . . 31118.9.4 Implementation. . . . . . . . . . . . . . . . . . . . . 313

18.10Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31318.11Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313

A Grammar for BETA 315

B The MjŒlner BETA System 321

Bibliography 323

Index 333

Trademark noticeMacintoshTM is a registeredtrademarkof AppleComputer, Inc.UNIXTM is a registeredtrademarkof AT&T Bell Laboratories.TheX Window Systemis a registeredtrademarkof MIT.Design/OA is a registeredtrademarkof MetaSoftwareCorporation,CambridgeMA, USA.SimulaTM is a trademarkof a.s.Simula.

Page 12: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 1

Intr oduction

This is first and foremosta book on the programminglanguageBETA, butit is alsoa book on object-orientedprogramming,andissuessuchasobject-orientedanalysisanddesignarealsocovered.

Introducinga programminglanguageis not just a matterof introducinglanguageconstructsand giving guidelinesand hints on how to use them.It is also a matterof introducinga way of thinking that is associatedwiththe underlying conceptualframework. For languagesbasedon well es-tablishedunderlyingconceptssuchas functions,relationsor equations,theway of thinking may be obtainedfrom other sources,and will often bepart of the backgroundandeducationof the prospective programmers.Forobject-orientedprogrammingthereis no well establishedtheoryor concep-tual framework. Furthermore,there is no establishedconsensuson whatobject-orientationis. Despitethis, a large numberof programmerspracticeobject-orientedprogramming.They usea numberof differentlanguagessuchas Simula (Dahl et al., 1968), Smalltalk (Goldberg andRobson,1989), C++(Stroustrup,1991), Eiffel (Meyer, 1988), and CLOS (Keene,1989). Theselanguageshave a commoncoreof languageconstructswhich to someextentmake themlook alike.

1.1 Benefitsof object-orientation

It is difficult to discussthebenefitsof object-orientationwithout first definingit. BeforeintroducingtheBETA approach,however, we shall briefly discusswhat the benefitsof object-orientationareconsideredto be. Therearethreemainbenefits:real world apprehension, stability of designandreusabilityofbothdesignsandimplementations.Whenpeopledisagreeaboutwhatobject-orientationis, it is oftenbecausethey attachdifferentlevelsof importancetotheseaspects.We considerall threeaspectsto be important,thoughperhapsnot equallyso.

1

Page 13: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

2 INTRODUCTION

Real world apprehension

Oneof the reasonsthat object-orientedprogramminghasbecomeso widelyacceptedis that object-orientationis closeto our own naturalperceptionofthe real world. (KrogdahlandOlsen,1986)(translatedfrom Norwegian) putit this way:

‘The basicphilosophyunderlyingobject-orientedprogrammingisto maketheprogramsasfaraspossiblereflectthatpartof thereal-ity they aregoingto treat.It is thenofteneasierto understandandto getanoverview of what is describedin programs.Thereasonis thathumanbeingsfrom theoutsetareusedto andtrainedin theperceptionof what is goingon in therealworld. Thecloserit ispossibleto usethis way of thinking in programming,theeasieritis to write andunderstandprograms.’

In (CoadandYourdon,1990)it is statedin thefollowing way:

‘Object-orientedanalysisis basedupon conceptsthat we firstlearnedin kindergarten:objectsandattributes,classesandmem-bers,wholesandparts.’

Both of thesequotationsstressthat one importantaspectof programdevel-opmentis to understand,describeand communicateaboutphenomenaandconceptsof theapplicationdomain.Object-orientedprogramminghasturnedout to beparticularlywell suitedfor doingthis.

Stability of design

The principle behind the JacksonSystem Development (JSD) method,(Jackson,1983) alsoreflectsoneof thebenefitsof object-orientation.Insteadof focusingon thefunctionalityof a system,thefirst stepin thesystem’s de-velopmentaccordingto JSD is to make a physicalmodelof the real worldwith which thesystemis concerned.This modelthenformsthebasisfor thedifferentfunctionsthatthesystemmayhave. Functionsmaylaterbechanged,andnew functionsmaybeaddedwithout changingtheunderlyingmodel.

As we shall seelater, the notion of a physicalmodel as introducedbyJSDis centralto object-orientationasdescribedin this book. The conceptsandtechniquesusedby theJSDmethodto developa physicalmodel,andtosubsequentlyimplementit onacomputerare,however, quitedifferentfrom theconceptsandtechniquesof object-orientedprogrammingaspresentedin thisbook. As mentionedabove, object-orientedprogrammingprovidesa naturalframework for modelingtheapplicationdomain.

Page 14: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

1.2 OBJECT-ORIENTEDPROGRAMMING AND BETA 3

Reusability

Onewell known problemwith softwaredevelopmentis beingable to reuseexisting softwarecomponentswhendevelopingnew ones.The functionalityof anexistingcomponentis oftenverysimilar to oneneededfor anew system.Theremay, however, be importantdifferenceswhich make it impossibletoreusetheexistingcomponent.For thisreason,thenew componentis oftenim-plementedby copying andmodifying theexisting component,but this meansthat it mustbe testedagain. More problematic,however, is that the relationsbetweenthe old andnew componentsmay be lost: if an error is detectedinone,it mustbecorrectedin both.Also,changesto commonpartsof thesystemmayhave to beperformedin bothcomponents.

Oneof thebenefitsof object-orientedprogramminglanguagesis thattheyhave strongconstructsfor supportingincrementalprogrammodification.It ispossibleto defineanew componentasanincrementalextensionof anexistingone,thuspreservingtherelationsbetweenthetwo components.Most object-orientedlanguagesarebasedon the class/subclassmechanism(inheritance)which first appearedin Simula. Oneof the main contributionsof Smalltalkwasthattheselanguageconstructswerecombinedwith theflexibility of Lispsystems.

Even without the flexibility of Smalltalk, the ability to createprogramsby meansof incrementalextensionis consideredto bethemainadvantageofobject-orientedprogrammingby many programmers.Thedisadvantageof in-crementalmodificationis that the library of componentsreflectsthe historicdevelopmentof thosecomponents.In addition, the relationsbetweencom-ponentsaremainly dictatedby maximalcodesharing,oftenconflicting withthemodelingrequirementsdiscussedabove. Thesepotentialconflictsbetweenrequirementswill bediscussedlater.

1.2 Object-oriented programming andBETA

To program is to understand: The developmentof an informationsystemis not just a matterof writing a programthatdoesthe job. It is of theutmostimportancethat developmentof this programhasrevealedan in-depthun-derstandingof theapplicationdomain;otherwise,theinformationsystemwillprobablynotfit into theorganization.Duringthedevelopmentof suchsystemsit is importantthatdescriptionsof theapplicationdomainarecommunicatedbetweensystemspecialistsandtheorganization.

Theapproachto object-orientedprogrammingpresentedin this bookem-phasizesthe modelingcapabilities. Most treatmentsof object-orientedpro-grammingare concernedwith languageconstructs,and thosefamiliar with

Page 15: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

4 INTRODUCTION

the literaturewill know that conceptslike inheritanceandmessagepassingareimportantconsiderations.Thereis, however, moreto object-orientedpro-grammingthanlanguageconstructs(this shouldbetruefor any programminglanguage).Theunderlyingconceptualframework or semanticsis just asim-portantasthelanguage.

Otherprogrammingperspectivesarebasedon somemathematicaltheoryor model,giving thema soundtheoreticalbasis,but object-orientedprogram-minglacksaprofoundtheoreticalbasis.For object-orientedprogramming,theinitial observation of how peopleunderstandthe world hasto be formulatedin a theoryor conceptualframework. For thebenefitof designinga program-ming language,and for the benefitof conveying an understandingof thesebasicconceptsaspart of a book on the language,this modeldoesnot haveto be formal. In fact, the modelunderlyingobject-orientationis by its verynatureinformal, althoughpart of the modelhasbeenformalizedin termsofprogramminglanguages.This is necessaryin orderto createdescriptionsthatmaybeexecutedon a computer. BETA maybeseenasa formal notationfordescribingthosepartsof theapplicationdomainthatcanbeformalized:BETAis formal in thesensethatdescriptionsmadein it haveaprecisemeaningwhenexecutedonacomputer. Often,aprogramminglanguageis definedin termsofa mathematicalmodel,yet sucha modelhasnot beenconstructedfor BETA,althoughit mightbeusefulfor thepurposeof consistency checkingandformalverification.

This book attemptsto go beyond languagemechanismsand contributea conceptualframework for object-orientedprogramming.This framework,however, needsfurtherdevelopment.

Weshall introducethenotionsof physical modeling, to capturemodelingof partsof theworld basedupontheidentificationof phenomenaandconcepts,andthenotionof thephysical model, to denotethemodelsthatarecreatedinthis process.

Theuseof informalconceptsin thesystemdevelopmentprocessis impor-tant, however, thereis a tendency to put a greateremphasison the conceptsthat canbe formulatedin termsof a programminglanguage.The reasonisclear, sincethe systemdevelopmentprocesseventuallyhasto result in a de-scriptionthatcanbeexecutedonacomputer. Thisbookalsoemphasizescon-ceptsthat canbe describedin BETA. Below we briefly summarizethe roleof BETA in the systemdevelopmentprocess.Traditionally, systemdevelop-mentis organizedinto analysis, designandimplementation, andtheconceptsof object-orientationmaybeappliedto all of theseactivities.

� Analysis.Theprimarygoalof analysisis to understandtheapplicationdo-main.In thisactivity, relevantconceptsandphenomenafromtheapplicationdomainmustbeidentifiedanddescribed,usuallyinvolving thesystemto bedeveloped.For this reason,it is importantthattheconceptsandphenomenaidentifiedcanbe communicated.In this processit is useful to usea high

Page 16: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

1.2 OBJECT-ORIENTEDPROGRAMMING AND BETA 5

numberof informal descriptions,sinceit would otherwisebequitedifficultto communicatethosedescriptionsto noncomputerspecialists.The infor-mal descriptionsmayconsistof a mixtureof text, graphics,andsometimesalsoincompleteprogramfragments.Theuseof graphicsin systemdescrip-tions is important,particularly in analysisas it might be importantto usegraphicalnotationfor partof thedescriptions.

� Design. The designactivity is concernedwith constructinga precisede-scriptionthatcanberefinedinto anexecutableprogram.Heretheinformalconceptsdevelopedin the analysisactivity have to be madeinto formalconceptsthatcanbedescribedby a programminglanguagelike BETA. Atthis level the object-orientedprogramwill be a descriptionof phenomenaandconceptsfrom the applicationdomain. Sucha programwill be fairlyabstract,sinceit will includeanumberof elementsthatneedfurtherrefine-mentbeforeit canbeexecuted.It is, however, importantthatthedescriptionis relevantfor theapplicationdomain.

Graphicalnotationmayalsobeusefulin thedesignactivity. Mostprogram-minglanguageslikeBETA haveatextualsyntax,but it mayoftenbeadvan-tageousto usegraphicalnotationsfor partof theprograminsteadof textualrepresentation.Later we shall discusshow the sameunderlyinglanguageprinciplesmaybepresentedbothgraphicallyandtextually.

Analysisanddesignaresimilar in the sensethat the descriptionsmustbemeaningfulin termsof the applicationdomain. They are different withrespectto their useof informalandformal descriptions.

� Implementation.This is concernedwith implementingthe designdescrip-tion on a computer, i.e. elementsrepresentingconceptsand phenomenafrom the applicationdomainmustbe describedin termsof conceptsthatcanbe executedon the computer. Thesecomputerconceptsdo not repre-sentconceptsandphenomenafrom theapplicationdomain,i.e. theprogramis extendedwith detailsthataremeaninglessin theapplicationdomain.Thebasicprinciplesof the two levels are the same;it is programming,but atdifferentlevels.

Designandimplementationaresimilar in thesensethataprogramminglan-guageis usedfor thedescriptions.They differ in thesensethattheelementsof a designdescriptionmustbemeaningfulin termsof theapplicationdo-main,whereasthis is not thecasefor animplementationdescription.

Systemdevelopmentmethods

The above descriptionof analysis,designandimplementationmay give theimpressionthattheseactivities areorderedin time (i.e. first analysis,thende-sign,andfinally implementation),but this is not thecase.In somesituationstheseactivities may be intermixed, andthe developermay not be conscious

Page 17: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6 INTRODUCTION

of them. Thereare variousmethodsof organizingthe systemdevelopmentprocesswhich differ in a numberways. The object-orientedframework pre-sentedin this book is not associatedwith any specificmethod,althoughit isnot completelyindependent(we returnto this in Chapter18).

Logical versusphysical systemstructure

BETA is a languagefor describingasystem(programexecution)consistingofobjectsandpatterns,someof which representphenomenaandconceptsfromthe applicationdomain,andotherswhich are for implementationpurposes.TheBETA objectsandpatternsprovide the logical structure of a system;theBETA languageprovidesmechanismsfor describingthis logical structure.

A BETA program(or BETA description)is usuallyconstructedin theformof text in oneor morefiles. The programmay exist in a numberof variantsfor differentcomputers,andit may exist in variousversions.Part of it mayconsistof modulesincludedfrom a library; partmaybeusedin many differ-entprograms.TheBETA languagedoesnot have mechanismsfor describingthe physicalorganizationof a BETA programin termsof files, variants,andversions,etc.,becausethephysicalstructureof theprogramtext is consideredto be independentof the logical structureof the program. Somelanguagesprovide languageelementsfor handlingthe physicalstructure,e.g.modulesareoften divided into interfaceand implementationmodules. Suchmecha-nismsarenot a partof BETA. Instead,a language-independenttechniquefororganizingthephysicalstructureof a programtext hasbeendeveloped.Thistechniqueis basedon the context free grammarof the language,whereanycorrectsequenceof terminalandnonterminalsymbols(a so-calledsententialform) of thegrammarcanbea module. This techniquecanbeusedfor lan-guagesotherthanBETA. Chapter17 describestechniquesfor organizingthephysicalstructureof aBETA program.

Thereareaspectsof the physicalstructureotherthanorganizationof theprogramtext. A BETA systemconsistsof a numberof objectsexecutingac-tions,andtheactionsexecutedby objectsmaytakeplaceconcurrently.

Someof theobjectsof a BETA systemaretransientin thesensethattheyonly exist while theprogramis executing.Otherobjectsarepersistentin thesensethatthey maybestoredonsecondarystoragesuchasa diskandsurvivethe programthat createdthem. They may then be readand usedby otherprograms. The separationof objectsinto transientandpersistentobjectsisnot partof theBETA language,but is handledby theMjølner BETA System.An object-orienteddatabasesystemsupportingclient andserversis currentlybeing developedon top of the persistentobject storeof the Mjølner BETASystem.

Moderncomputerhardwareoften consistsof a large numberof proces-sorsconnectedthroughsomecommunicationmedia,an examplebeinga set

Page 18: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

1.2 OBJECT-ORIENTEDPROGRAMMING AND BETA 7

of workstationsconnectedthrougha local areanetwork. Theconcurrency de-scribedin a BETA programmayberealizedthroughtime sharingon a singleprocessor, or by distributing theactive BETA objectson a numberof proces-sors. BETA hasconstructsfor describingthe logical structureof concurrentobjects,andthephysicalstructureof mappingconcurrentobjectsontoseveralprocessorsis consideredindependentof the language. The Mjølner BETASystemcontainssomesupportfor distributedcomputingin BETA.

For thephysicalstructure,only modularizationis describedin this book.Themappingof aBETA systemontoaprocessgenerator(computerhardware)in termsof splitting objectsinto transientandpersistentobjects,andthedis-tribution of objectsontoseveralprocessors,is not dealtwith in this book(seetheMjølner BETA Systemmanualsfor thecurrentstatusof this).

Although the main emphasisin this book is on the logical structureof asystem,thedesignandimplementationof thephysicalstructureis equallyim-portant.During designandimplementation,theprogrammermustbeexplicitabout the physicalorganizationof the programtext, as describedin Chap-ter 17, andshouldbe concernedwith the organizationof persistentanddis-tributedobjects.

BETA

BETA is a modernlanguagein the Simula tradition. It supportsthe object-orientedperspective on programmingand containscomprehensive facilitiesfor proceduraland functionalprogramming. Researchis going on with theaim of includingconstraint-orientedconstructs.

BETA replacesclasses,procedures,functionsand typesby a single ab-stractionmechanismcalledthe pattern. It generalizesvirtual procedurestovirtual patterns,streamlineslinguisticnotionssuchasnestingandblockstruc-ture,andprovidesa unified framework for sequential,coroutineandconcur-rentexecution.Theresultinglanguageis smallerthanSimulain spiteof beingconsiderablymoreexpressive.

The Mjølner BETA Systemis a softwaredevelopmentenvironmentsup-porting the BETA languagewhich includesan implementationof the BETAlanguageasdescribedin this book. In addition,thesystemincludesa numberof othertools,anda largecollectionof librariesandframeworks thatgreatlyenhanceBETA’s usabilityby providing a largenumberof predefinedpatternsand objects. (The libraries and frameworks are not describedin this book,thoughashortintroductionis givenin AppendixB. For adetaileddescriptionseetheMjølner BETA Systemmanuals.)

TheMjølnerBETA Systemwasoriginally developedaspartof theNordicMjølner project, which hasalso produceda large numberof other results.(Knudsenet al., 1992) is a collectionof theproject’smainresults.

Page 19: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

8 INTRODUCTION

1.3 Notes

In the early 1960s,the Simula I languagewas introducedwith the purposeof writing simulationprograms. In the late 1960s,a generalprogramminglanguage,Simula67, wasdefined,the importantcontribution of which wasthe introductionof theclassandsub-classconceptsandthenotionof virtualprocedures.Theseconstructshave becomethe coreof mostobject-orientedlanguages.WhereasSimulaI wasa simulationlanguage,Simula67 is a gen-eralprogramminglanguagethatsupportssimulationby meansof ageneralsetof classes.This demonstratedthepower of theSimulaconcepts.InstancesofSimula classesbehave like coroutines,making it possibleto simulatecon-currency, which was heavily usedin the simulation package. Despitetheusefulnessof coroutinesandquasi-parallelsequencingfor modelingreal-lifephenomena,theseconceptshave not yet found their way into most object-orientedlanguages.For a further descriptionof the history of Simula, see(NygaardandDahl,1981).

Simula hasbeenusedby a relatively small communityfor many years.In theearly1970s,theclass/sub-classconceptswereusedin thedesignof theSmalltalklanguage,leadingin turntoamajorbreakthroughfor object-orientedprogramming.TheSmalltalkstyleof programminghasparticularlycaughtonin Lisp communities,resultingin a numberof substantialcontributions likeFlavors(Cannon,1982), andLoops (Bobrow andStefik,1983).

The object-orientedideashave alsostartedto impacton traditionalsoft-wareconstruction,themostinfluentialseemingto beC++. Anothercontribu-tion is Eiffel.

In the 1970s,muchattentionwasgiven to the notionof structured pro-gramming. Thediscussionsof object-orientedprogrammingin theliteraturemay be comparedto that of structuredprogramming. Structuredprogram-ming wasoftenassociatedwith avoiding goto’swhenprogramming,yet thereis clearlymoreto structuredprogrammingthanavoidinggoto’s,justasthereismoreto object-orientedprogrammingthaninheritanceandmessagepassing.

The label ‘object-orientation’ is attachedto many things. Peopletalkaboutobject-orientedprogramming,object-orienteddesign,object-orientedimplementation,object-orientedlanguages,object-orienteddatabases,etc.Object-orientationhasstartedto be appliedto theseactivities, i.e. conceptssuchas object-orientedanalysis,object-orienteddesignand object-orientedimplementationhave arrived. Often, object-orientedprogrammingis as-sociatedwith object-orientedimplementation. The reasonfor this is thatobject-orientationoriginatedfromprogramminglanguagessuchasSimulaandSmalltalk.In thisbook,object-orientedprogrammingis meantto coverobject-orientedanalysis,object-orienteddesignandobject-orientedimplementation.

Object-orientationhas also generatedparticular interest in the areaofdatabasesystems.A bookonobject-orienteddatabasesshouldcover thesame

Page 20: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

1.3 NOTES 9

materialasthisbook,sincethebasicprinciplesarethesame.A databasebookmightpaymoreattentionto thehandlingof largesetsof information.Databasedesignandprogrammingarebothrelatedto modeling/representingrealworldphenomena.

A programminglanguageis oftencharacterizedasanobject-orientedlan-guage,afunctionallanguage,aprocedurallanguage,etc.Also, thetermmulti-perspective (or multi-paradigm ) languageis usedfor languagessupportingmorethanoneperspective. Oftentheterm‘object-orientedlanguage’is usedexclusively for languagesthatonly supportobject-orientation.In thisbook,anobject-oriented language is a programminglanguagethat supportsobject-orientedprogramming,anda pure object-oriented languageis a program-ming languagethat only supportsobject-orientation. The samedefinitionsapplyto otherperspectives.

Page 21: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

10 INTRODUCTION

Page 22: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 2

Intr oduction to BasicConcepts

In thischapterwebriefly andinformally introducesomeof thebasicconceptsunderlyingobject-orientedprogramming.They arefurther explainedduringthe introductionof the BETA languagein subsequentchapters,anda moredetailedtreatmentis givenin Chapter18.

A computerexecutingaprogramgeneratesaprocessconsistingof variousphenomena(an exampleof a phenomenonis an object representinga bankaccountof somecustomer).Suchan object representscertainpropertiesofthe realbankaccount,like its balance,anda list of depositsandwithdrawalsperformedon theaccount.Theobjectsresidein thecomputer’smemory.

In therealworld, customersandbankclerksperformactionsthatchangethe stateof the variousbankaccounts.At a certainpoint, the balanceof agiven accountmay be DKK 5000, but a depositof DKK 105 will changeits balanceto DKK 5105. A depositis oneexampleof an actionperformedin a bank; otherexamplesarethe withdrawal of money, the computationofinterest,openingandclosingof accounts,etc. It is importantto be awareofthe fact thatactionsareorderedin time – in mostbanksyou have to depositsomemoney beforeyoucancarryoutawithdrawal.

Theprocessgeneratedby thecomputerhasphenomenarepresentingtheseactionsandstates.Thestateof abankaccountis representedby theobjectrep-resentingthebankaccount,andactionschangingthestateof thebankaccountarerepresentedby actionsexecutedby thecomputer.

For a setof objectsrepresentinga banksystem,we may be interestedinmeasuringpart of the stateof several accounts,which could, for instance,consistof computingthebalanceof all agivencustomer’saccounts.

A processgeneratedby a computerexecutinga programis calleda pro-gram execution. Programexecutionsbelongto a classof processescalledinformationprocesses. The productionprocessof carsin a factory, the pro-cessingof customerordersin a company, andthemoney flow betweenbanksmaybeviewedasinformationprocesses.

Thestudyof informaticsor computerscienceis concernedwith thestudy

11

Page 23: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

12 INTRODUCTIONTO BASIC CONCEPTS

of information processes.This book will develop a conceptualframeworkfor understandinganddescribinginformation processes,in particularbeingconcernedwith programexecutions. In Chapter18 we return to the moregeneralnotionof informationprocesses.

BETA is aprogramminglanguage for describingprogramexecutions,andthemainpartof this bookis aboutBETA.

2.1 Perspectiveson programming

To understandobject-orientedprogrammingit is necessaryto understandhowit relatesto otherperspectiveson programming.The purposeof this sectionis to giveashortintroductionto someof themostgenerallyacceptedperspec-tives, thoughit is not intendedto be a completedescriptionof the subject.Readersareencouragedto consultotherreferencesfor this purpose.

In theliterature,a largenumberof programmingperspectives,suchaspro-cess,typesystemandeventperspectivesarediscussed,becauseprogrammershave differentperspectiveson programming(in principle, eachprogrammermay have his own perspective). Also, the definitionsof perspectivesgivenbelow might not coincidewith what other peopleunderstandby theseper-spectives.

2.1.1 Proceduralprogramming

Whencomputerswereinventedthey wereviewed asprogrammablecalcula-torsandmany peoplestill hold this view.

Considerasimplecalculator. It mayconsistof aregisterfor storingavalue,andanumberof operationssuchasadd,sub,mult anddiv. It is possibleto en-ter anumberinto theregisterandthenmodify this valueusingtheoperations.Thefollowing is a list of possibleoperationsfor asimplecalculator:

enter Vadd Vsub Vmult Vdiv Vresult

The operationsenter, add, sub, mult, div and result correspondtobuttonsonthecalculator;V correspondsto anumberenteredthroughanumberpad. We arenot concernedwith thephysicallayoutof thecalculatorhereasweareonly interestedin its functionality.

Insteadof oneregisterthe calculatormay have several registers,thusin-termediateresultsof acalculationmaybestoredin theseregisters– with only

Page 24: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

2.1 PERSPECTIVESON PROGRAMMING 13

one register the userwould have to write down intermediateresultson pa-per. Assumethatour calculatoris extendedwith registersR0, R1, R2, ...Rn, andthatthepreviousoperationsoperateonR0. Wehavethefollowing newoperations:

enter V Riadd Ri Rjsub Ri Rjmult Ri Rjdiv Ri Rjcopy Ri Rj

TheoperandsRi andRj correspondto buttonsfor selectinga register.A calculatorwith a fixednumberof registersandoperationshasa limited

scopeof applications.Oftentheuserhasto carryout thesameprocedureoverandover againon differentdata,perhapscarryingout the samesequenceofoperations.This leadto theideaof aprogrammablecalculator. In additiontodataregistersandoperations,a programmablecalculatorhasa storewhereasequenceof operationsmaybestored:

define Pi Op1; Op2; ... endcall Pi

Thedefine andcall operationscorrespondto buttonsfor definingandcall-ing procedures.Pi couldbea numberor anotheruniqueidentificationof theprocedurebeingdefined.Our programmablecalculatorcouldbe usedin thefollowing way:

define P1: copy R0 R1; mult R0 2; add R0 R1 endenter 100call P1return

Thestoreusedfor storingproceduresmayalsobeusedfor storingvalues,i.e.it is possibleto move a valuefrom a registerto the store,andvice versa. Inthis way, it is possibleto savea largenumberof intermediateresults.

In the above examplesit waspossibleto definea procedureby meansofa sequenceof operations,but for many typesof calculationsthis is too primi-tive. Theoperationsmaybeextendedwith controlflow operations,makingitpossibleto selectfrom betweensub-sequencesof operationsandto repeattheexecutionof a sub-sequence.Thefollowing is anexampleof possiblecontrolflow operations:

L:goto Lif Ri=0 goto L

Page 25: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14 INTRODUCTIONTO BASIC CONCEPTS

Thefirst computerswerejustadvancedprogrammablecalculatorswith alargenumberof registers,a large storefor saving proceduresanda suitablesetofbasicoperations.

With programmablecalculatorsit is possibleto solve large calculations;with computers,evenlargeronescanbesolved.

One problemwith our programmablecalculatoris that the programmermustkeeptrackof whichpartof thestoreis usedfor valuesandwhichpartforprocedures.To help,asymbolicassemblermaybeused,whereit is possibletodeclarea numberof variablesby meansof names.Theassemblerallocatesamemorycell correspondingto eachvariable,sotheprogrammercanthenreferto avariable/registerby nameinsteadof by anumber.

It is, however, difficult andtime consumingto write proceduresusingthesimplelanguageof thecomputer. Instead,ahigh-level programminglanguagemay be used. A compiler is usedto translatea programwritten in the pro-gramminglanguageinto thelanguageof thecomputer. Thefirst programminglanguageshad facilities for definingvariablesandprocedures(variablesaresimply registers).Insteadof afixednumberof registers,theprogrammermaydefinethenumberof variablesneeded,which is, of course,limited by thesizeof the store. We do not go into further detail aboutprogramminglanguageshere,sincethis will bedealtwith in therestof thebook.

Despitethe fact that thereis a hugedifferencebetweensimple calcula-torsandmoderncomputers,a computeris still viewedby mostprogrammersasan advancedcalculator. Whenwriting a program,the programmerthinksof defininga setof variablesanda setof proceduresfor manipulatingthesevariables.This perspectiveon programmingis calledprocedural (or impera-tive) programming. In summary, proceduralprogrammingmaybedefinedasfollows:

Procedural programming. A programexecutionis regardedasa (partiallyordered)sequenceof procedurecallsmanipulatingvariables.

As mentionedabove, proceduralprogrammingis still themostcommonper-spective on programming,supportedby languageslike Algol (Naur, 1962),Pascal(JensenandWirth, 1975), C (KernighanandRitchie, 1978) andAda(US Departmentof Defense,1980). It is in nowayobsolete,still beingusefulfor writing smallproceduresand,asweshallseelater, it maybeusedtogetherwith object-orientedprogramming.

2.1.2 Functional and constraint programming

Sincethemid-1960s,a largeresearcheffort hasbeendirectedtowardsgivinga mathematicaldefinitionof programminglanguages.Onemainresultof thisis thenotionof functionalor (applicative) programming. Whentrying to give

Page 26: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

2.1 PERSPECTIVESON PROGRAMMING 15

amathematicaldefinitionof programminglanguages,it turnedout thattheno-tions of ‘variable’ and ‘assignment’werethe main bottlenecks.In practice,many programmershave realizedthatwhenwriting largeprogramsit is diffi-cult to handlethelargenumberof variables.Oneresponseto this is functionalprogramming,in which a programis viewed asa mathematicalfunction. Aprogramis thenacombinationof mathematicalfunctions.

A languagesupportingfunctionalprogrammingmust,then,includefacili-tiesfor definingmathematicalfunctions,includinghigherorderfunctions,i.e.functionsthat may have functionsasparametersandreturn functionsasre-sults.In addition,sucha languageshouldincludedatatypescorrespondingtomathematicaldomains.

Lisp is anexampleof a languagewith excellentsupportfor functionalpro-gramming.However, Lisp is notapurefunctionalprogramminglanguageasitsupportsotherperspectivesaswell, includingproceduralandobject-orientedprogramming.ML andMirandaareexamplesof purefunctionallanguages.

Themostprominentpropertyof thefunctionalperspective is thatthereareno variablesandno notionof state.A variablemayonly beboundonceto avalue,andit is notpossibleto assignanew valueto avariable.

To summarize,functionalprogrammingmaybedefinedasfollows:

Functional programming. A programis regardedasa mathematicalfunc-tion, describinga relationbetweeninput andoutput.

Like proceduralprogramming,functionalprogrammingshouldbe seenasasupplementto proceduralandobject-orientedprogramming. It is useful fordescribingstatetransitionswheretheintermediateresultsareirrelevant.

The notion of functional programminghasbeengeneralizedfurther. Afunctionis a relationwhich is uniquein its first element.Insteadof just view-ing a programasa functionalrelation,it might aswell beviewedasa generalrelation(orasetof equations).Thisis theideaof so-calledlogicprogramming,rule-basedprogramming, or asweshallcall it here,constraint programming:

Constraint programming. A programis regardedasa setof equationsde-scribingrelationsbetweeninput andoutput.

Thisconstraint-orientedperspective is supportedby, for example,Prolog.We shallnot go into furtherdetailson functional-andconstraint-oriented

programming(readersare encouragedto consult (Wikstrm, 1987; Leler,1987). It is importantto stressthatdifferentperspectivesshouldnot excludeeachother– they areeachuseful for differentpurposes,anda programmershouldhave the possibility of usinga given perspective whenrelevant. Theidealprogramminglanguageshouldintegratethedifferentperspectives. It isimportantto be awarethat this shouldnot be doneby designinga languageconsistingof featuresfrom variousprocedural,functionalandobject-oriented

Page 27: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16 INTRODUCTIONTO BASIC CONCEPTS

languages.A programminglanguageshouldbebasedon a conceptualframe-work, and the languageconstructsshouldbe designedwith respectto thisframework.

2.2 Object-oriented programming

This sectiongivesan informal introductionto object-orientedprogramming,definedasfollows:

Object-oriented programming. A programexecutionis regardedasa phys-ical model,simulatingthebehavior of eithera realor imaginarypartoftheworld.

The notion of a physicalmodel shouldbe taken literally. Most peoplecanimaginetheconstructionof physicalmodelsby meansof, for example,Legobricks. In the sameway, a programexecutionmay be viewed asa physicalmodel.Otherperspectiveson programmingaremadepreciseby someunder-lying modeldefiningequations,relations,predicates,etc. For object-orientedprogramming,however, wehave to elaborateon theconceptof physicalmod-els.

Physicalmodelsarenot just relevant for computers.In the following wegiveexamplesof physicalmodelswherecomputersarenot involved.

2.2.1 Manual systems

In many areasit is commonto make a physicalmodelof someconstructionso asto observe somepropertiesbeforethe ‘real thing’ is constructed.Thisis the casewith buildings: beforeconstructinga large building, a model isusuallymadeto checkvariouspropertiesof thedesign.This is alsothecasefor bridges,cars,trains,aeroplanes,etc.

Whenbuilding a railway systemit is commonto modelit usinga modeltrainset.Suchamodelmaysimulatemany of thepropertiesof the‘real’ trainsystem.The following is a descriptionof how manualtrain seatreservationwashandledin Norway (andprobablyin othercountriesaswell) beforecom-puterswereinvented.Manualtrain seatreservationswerebasedon a numberof sheetsrepresentingthe wagonsin the train. The upperpart of Figure2.1showsthecollectionof sheets,andthelowerpartshowsexamplesof two suchsheets.Theseatscouldbechecked,or thepartof thetrip wheretheseatwasoccupiedcouldbeindicated.Travelersweregivensmallticketsindicatingthedetailsof their reservation.

Sucha train reservation systemis an exampleof what we considerto bea physicalmodel. Eachwagonin a train is representedby a sheet,which in-cludesthosepropertiesof thewagonthatareessentialfor seatreservation.The

Page 28: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

2.2 OBJECT-ORIENTEDPROGRAMMING 17

Carriage no. 16 Carriage no. 17

Figure2.1 Manualseatreservationsystem.

systemwasflexible in termsof thekindsof serviceswhichcouldbesupplied,e.g.thereservationof aseatnext to anotherseat,thereservationof aseatcloseto thedoor, etc.,wereall possible.Entrieswereof coursewritten in pencil toallow easyupdating.Thereservationsheetswerekeptat thetrain’s departurestationsothey couldbesentwith theguard.

Hospitalsprovide anothersuchexample. At a hospitala medicalrecordcorrespondingto eachpatientkeepstrackof the relevant informationrelatedto that patient. This recordmay be consideredto be a representationof thepatient.

2.2.2 Computerizedphysical models

In theabove examples,differentkindsof physicalmaterialareusedfor con-structingthe physicalmodel. In computerizedphysicalmodels,objectsarethe materialusedfor representingphysicalphenomenafrom the application

Page 29: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18 INTRODUCTIONTO BASIC CONCEPTS

domain. Objectsare thus consideredas similar to cardboard,sheets,Legobricks,etc.,in thesensethatobjectsarephysicalmaterialthatmaybeusedforrepresenting(or modeling)physicalphenomena.Objectsare computerizedmaterial. In this way, objectsdiffer from materialsuchascardboard,paper,Legobricks,etc.

An objectis a pieceof physicalmaterialthatmaybeusedto represent(ormodel)a realor imaginaryphenomenonfrom theapplicationdomain.Some-times we say that an object representsa phenomenonfrom the applicationdomain,andsometimeswesaythatanobjectmodelsaphenomenon.

In thefollowing wepresentexamplesof differentkindsof propertiesusedto characterizephenomena,andexplainhow they arerepresentedasobjects.

Object attrib utes

Objectsarecharacterizedby variousattributes, whichrepresent/modelaprop-ertyof thephenomenonbeingmodeled.Therearedifferentkindsof attributeswhich may be associatedwith objects. In the following someexamplesaregiven.

In aflight reservationsystemtherewill typically beanobjectrepresentingeachreservation. Thepropertiesof a reservationmayincludethedatefor theflight, a referenceto thecustomer, thesourceanddestinationof theflight, etc.An objectrepresentingareservationwill thenhaveattributescorrespondingtotheseproperties.An objectcorrespondingto a medicalrecordwill typicallyincludeattributesrepresentingpropertiessuchasthe temperatureandbloodpressureof thepatient,etc. Propertieslike thesearecalledmeasurableprop-erties.

A measurablepropertymayvary with time. The temperatureof a patientmay be differentat differentpoints in time. An objectmust thusbe abletorepresentthis variation,i.e. at differentpointsin time the attributemodelingmeasurablepropertiesmustresultin differentvalues.An objectis saidto haveastate. Thestateof anobjectvarieswith time.

Object actions

Many real world systemsarecharacterizedby consistingof phenomenathatperformtheirsequencesof actionsconcurrently. Theflight reservationsystemconsistsof severalconcurrentphenomena,e.g.flights andagents.Eachagentperformsits taskconcurrentlywith otheragents.Flightswill registerthe re-servation of seatsandensurethat no seatsarereserved by two agentsat thesametime. Note that this kind of concurrency is an inherentpropertyof thereality beingmodeled;it is not concurrency usedto speedup computations.

Complex taskssuchasthoseof theagentsareoftenconsideredto consistof several more or lessindependentactivities. This is so even thoughtheyconstituteonly onesequenceof actions,anddo not includeconcurrency. As

Page 30: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

2.2 OBJECT-ORIENTEDPROGRAMMING 19

an example,considerthe activities ‘tour planning’, ‘customerservice’ and‘invoicing’, whereeachof theseconsistsof asequenceof actions.

A singleagentwill not have concurrentactivities, but alternatesbetweendifferentactivities. Theshiftswill notonly bedeterminedby theagentsthem-selves,but will be triggeredby, for example,communicationwith otherob-jects.An agentwill, for instance,shift from tourplanningto customerservice(promptedby thetelephoneringing),andresumetour planningwhenthecus-tomerserviceis completed.

Theactionsequenceof anagentmayoftenbedecomposedinto partial ac-tion sequenceswhich correspondto certainroutinescarriedout several timesaspartof anactivity. As anexample,theinvoicingactivity maycontainpartialactionsequences,eachfor writing asingleinvoice.

Conceptsand abstraction

In the real world we createconceptsto capturethe complexity of the worldaroundus – we make abstractions.We all perceive the world in termsofconcepts:for peoplewe useconceptslike person,male,female,boy andgirl;in biologyweuseconceptslikeanimal,mammal,predator, fish anddog.

A conceptis a generalizedideaof a collectionof phenomena,basedonknowledgeof commonpropertiesof instancesin thecollection.Conceptsareusedto concentrateon thosepropertieswhich aresharedby a setof phenom-enain theapplicationdomain,andto ignorethedifferencesbetweenthem.

Whentalking aboutconcepts,it is usefulto identify thefollowing charac-teristics:

� The extensionof a conceptis the collectionof phenomenacoveredby theconcept.

� The intensionof a conceptis a collectionof propertiesthat in somewaycharacterizethephenomenain theextensionof theconcept.

� Thedesignationof a conceptis thecollectionof namesby which thecon-ceptis known.

Theextensionof theconceptpredatorcontainsall lions, tigers,cats,etc. Theintensionincludesapropertysuchas‘eatingmeat.’

Weusethetermpatternfor aconceptbelongingto acomputerizedmodel.A patternis thusa representationof a conceptin our computerizedmodel.

Organizationof knowledge

Peopleconstantlyusethefollowing threefundamentalmethodsof knowledgeorganizationfor understandingtherealworld:

Page 31: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

20 INTRODUCTIONTO BASIC CONCEPTS

anim� al

mam� mal fis� h bir� d reptile

pred�

ator rode� nt

lio� n tiger

Figure2.2 Partof aclassificationhierarchyfor animals.

� Identificationof phenomenaand their propertiesAs a first stepin under-standinga complex collection of phenomena,individual phenomenaandtheir propertiesarerecognized.An objectmay be observed to consistofcertainparts,have a certainsizeandweight,a certaincolor, etc. Similari-tiesbetweendifferentphenomenamaynot berealized,just asa systematicunderstandingof theindividualphenomenamaynotbeobtained.

� ClassificationClassificationis themeansby whichweform anddistinguishbetweendifferent classesof phenomena.Phenomenaand conceptswithsimilar propertiesaregroupedinto classescorrespondingto extensionsofconcepts.Thisprocessleadsto classificationhierarchies.

In Figure2.2, a hierarchyof conceptsrelating to biology is shown. Theconceptof ananimalmaybeviewedasmoregeneralthantheconceptsofmammal,fish, bird andreptile, sinceall mammals,fishes,birds andrep-tiles are alsoanimals. The conceptanimal is said to be a generalizationof mammal,fish, bird and reptile. Similarly, mammalis a more generalconceptthanpredatorandrodent,somammalis a generalizationof rodentandpredator. A conceptlike mammalis alsosaidto bea specializationofanimal.Similarly, predatoris a specializationof mammal.

Classificationhierarchiesareusefulfor understandingthe relevantproper-tiesof asetof phenomena.For theconceptanimalwemayassociateproper-tiescommonto all animals.Wemayassociatethepropertiescommonto allmammalsfor theconceptmammalasfor theotherconcepts.Sinceamam-mal, fish, bird or reptile is alsoananimal,we have isolatedtheir commonpropertieswith theconceptof animal.

� CompositionIn many situationsit is usefulto consideraphenomenaor con-ceptasa compositionof otherphenomenaandconcepts.Oneexampleofcompositionis to considera wholeasconstructedfrom parts. The partsmay againconsistof smaller, simpler parts. The notion of a whole/part

Page 32: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

2.2 OBJECT-ORIENTEDPROGRAMMING 21

Ma� n

He ad LeftA

rm Right�Arm LeftL� eg Right

�Leg

LeftH and RightHand LeftF� oot Right�Foot

Figure2.3 Whole/parthierarchyfor astickfigure.

Jim�

Jan� e Ma� ry Jo� e Mr. S� mith

mother father

wife boss

Figure2.4 Exampleof referencecomposition.

compositionis an importantmeansof understandingandorganizingcom-plex phenomenaandconcepts.

Figure2.3 shows an exampleof a whole/parthierarchyfor a stick figureconsistingof partslike head,body, armsandlegs. In turn, the legsconsistof lower leg, foot, etc. A car may similarly be viewed asconsistingof abody, anengine,four wheels,etc.

An objectrepresentinga personmay alsohave propertiessuchasspouse,father, boss,etc.Suchpropertiesarenotphysicalpartsof aperson.Instead,we may view a personobjectascomposedof referencesto otherobjects.This form of compositionis calledreferencecomposition, illustratedin Fig-ure2.4.

As mentionedbefore,theconceptualframework is discussedfurtherin Chap-ter18.

Page 33: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

22 INTRODUCTIONTO BASIC CONCEPTS

2.3 Exercises

(1) Design a calculatorcorrespondingto the abstractcalculatordescribedabove.

(2) Giveotherexamplesof physicalmodelsnot involving computers.

(3) Developaclassificationhierarchyfor vehicles.

(4) Developawhole/parthierarchyfor a tree.

(5) Designa simpletrain reservationsystem.

2.4 Notes

The conceptualframework for object-orientedprogrammingpresentedhereand in Chapter18 is a result of the BETA project, and hasformed the ba-sis for the designof BETA. It evolved over many years, and was influ-encedby several sources,including Simula, (Holbæk-Hanssenet al., 1975),(KnudsenandThomsen,1985), and a large numberof studentthesescar-ried out in Aarhus and Oslo. The Norwegian train example is from(Sørgaard,1988), andthestickfigureexampleis from(Blake andCook,1987).

Other important contributions to a framework for object-orientedpro-gramming may be found in (StefikandBobrow, 1984), (Booch,1986),(ShriverandWegner, 1987), (ECOOP1987–1992) and (OOPSLA 1986–1992).

Page 34: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 3

Objects and Patterns

Themostfundamentalelementsof BETA areobjectsandpatterns.Thischap-ter introduceslanguageconstructsfor describingobjectsandpatterns.

3.1 Overview

A BETA programexecutionconsistsof a collectionof objectsandpatterns.An object is somecomputerizedmaterialcharacterizedby a setof attributesandanactionpart. Someobjectsin a programexecutionwill representphe-nomenafrom theapplicationdomain,whereasotherobjectsarejustpartof theimplementation.

An objectrepresentinga bankaccountmaybedescribedin thefollowingway:

(# balance: ... ;Deposit: ... ;Withdraw: ... ;

#)

Thebankaccountobjectis characterizedby theattributesbalance, DepositandWithdraw . The attributebalance 1 representsthecurrentbalanceof theaccount,Deposit representstheactionsperformedwhenmoney is placedinthe account,andWithdraw representsthe withdrawals performed.The dots... indicatesomedetailsthathave beenleft out of thedescription.All otherpartsof thedescriptionhave a meaningin BETA. Thesyntacticconstruct(#... #) is calledan object-descriptor, which describesthe structure of anobject.Partof thestructureof anobjectis its attributeslikebalance , DepositandWithdraw . Laterwe shallseethat thestructureof anobjectmay includemorethanits attributes.

1SeealsoSection18.7for a discussionof how to representpropertieslike balance .

23

Page 35: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

24 OBJECTSAND PATTERNS

Singularly definedobjects

A personprogramminghis own privatefinancialsystemmay have only onebankaccount.In this case,thereis only a needto representonebankaccountin thesystem,describedasfollows:

myAccount: @(# balance: ... ;

Deposit: ... ;Withdraw: ... ;

#);

Theabovedescriptionhasthreeparts:

(1) myAccount is thenamethatmaybeusedto referto theobjectrepresentingtheaccount,

(2) thesymbol@showsthatmyAccount is thenameof anobject,and

(3) theobject-descriptor(# ... #) describesthestructureof theobject.

ThemyAccount namemaybeusedto denotetheattributesof thebankaccountobject.Theremote-name2 myAccount.balance denotesthebalanceattribute.Theotherattributesmaybedenotedin asimilarway.

ThemyAccount objectis calledasingularobject, sincetheobjectdescrip-tor (# ... #) is only usedfor describingasingleobject.

Patterns

In abankingsystemthereis clearlyaneedto representseveralbankaccounts,thus the systemincludesa pattern representingthe conceptof a bankac-count. The objectsrepresentingthe actualbank accountsmay then be de-scribedasinstancesof this pattern.Thepatternrepresentingtheconceptof abankaccountmaybedescribedasfollows:

Account:(# balance: ... ;

Deposit: ... ;Withdraw: ... ;

#);

Thepatterndescriptionhastwo elements:

(1) Account is thenameof thepattern,and

(2) theobject-descriptor(# ... #) describingthestructureof eachof thebankaccountinstances.

2SeealsoSection3.2.5.

Page 36: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.1 OVERVIEW 25

The differencebetweenthe descriptionof the myAccount object and theAccount patternis the useof the symbol@after : . The presenceof @after: meansthatanobjectis described.Whenthereis no symbolbetween: and(# ... #) , apatternis described.

Pattern-definedobjects

The Account patternmay, for instance,be usedto describethreebank ac-counts:

account1: @Account;account2: @Account;account3: @Account;

The descriptionof eachbankaccounthasthreeelementsthat aresimilar tothosefor the descriptionof myAccount . The differenceis the use of theAccount patterninsteadof (# ... #) to describethe structureof the ac-count objects. The namesaccount1 , account2 and account3 may all beusedlike myAccount . It is, for example,possibleto denotethe balanceofaccount1 usingtheremote-nameaccount1.balance .

The distinctionbetweendescribinga singular objectsuchasmyAccountanddescribinga patternrepresentinga conceptlike Account is important.Intheformer, oneis dealingwith asituationwherethereis only onesingleobjectto consider. In the latter, thereis a wholeclassof similar objectswhich maynaturallybe classifiedusinga concept.From a technicalpoint of view, it isconvenientto avoid inventinga patternnamewhen thereis only a singularobject.

Whenmakingdescriptionsin BETA thereis a large numberof patternsavailable for describingobjects. The integer patternis one example. In-stancesof the integer patterndescribeobjectsthat may representintegernumbers.In thebankaccountexample,theattributebalance couldberepre-sentedasaninstanceof the integer pattern:

balance: @integer

Declarations

The syntacticelementfor describingattributesis calleda declaration. Thefollowing areexamplesof declarationsusedabove:

Account: (# ... #);account1: @Account;balance: @integer

In general,thesyntacticconstruct: signalsa declarationof somekind, i.e. anamebeingassociatedwith someentity.

Page 37: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

26 OBJECTSAND PATTERNS

Description of actions

TheDeposit andWithdraw attributesrepresentthedepositingandwithdraw-ing actions,respectively, performedon an account.Theseattributesmay bedescribedasfollows:

Account:(# balance: @integer;

Deposit:(# amount: @integerenter amountdo balance+amount->balanceexit balance#);

Withdraw:(# amount: @integerenter amountdo balance-amount->balanceexit balance#);

#)

Deposit andWithdraw arepatterns.Deposit representsa conceptcoveringall possibledepositactions.The executionof an instanceof Deposit repre-sentsanactualdepositaction.An instanceof Deposit is anobjectconsistingof oneamount attribute representingtheamountof money to be put into theaccount. The depositaction is describedby enter amount do ... exitbalance .

An actionrepresentinga depositinto the account1 accountmay be de-scribedasfollows:

500->&account1.Deposit->newBalanc e

This describesthatan instanceof account1 ’s Deposit attribute is generated(describedby &account1.Deposit ). Thevalue500 is assignedto theamountattribute (describedby enter amount ), then the value of amount is addedto balance (describedby do balance+amount->balance ), andfinally, thevalueof balance is returned(describedby exit balance ) andassignedtotheobjectnewBalance .

Thesymbol& meansnew, andtheexpression&account1.Deposit meansthatanew instanceof thepatternaccount1.Deposit is createdandexecuted.Creationof aninstanceof a patternandexecutingit is oftencalledprocedureinvocation.

Withdraw workslike Deposit .

Page 38: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.1 OVERVIEW 27

Imperati ves

An imperative is a syntacticelementfor describingan action,of which thefollowing areexamples:

balance+amount->balance;500->&account1.Deposit->newbalance

Completeprograms

Until now, variouselementsof BETA descriptionshave beenshown. Theex-amplein Figure3.1 shows how to combinesomeof theseelementsinto onecompounddescriptionin the form of an object-descriptorhaving Account ,account1 , account2 andaccount3 asattributes. In addition,the attributesK1, K2 andK3 have beenadded.Thedo-partof theobject-descriptorconsistsof a sequenceof actionsperformingvariousdepositsandwithdrawalson theaccounts.This object-descriptormay be compiledandexecutedby a BETAprocessor.3 An object-descriptorthat may be executedis often calleda pro-gram.

An abbreviatedsyntaxfor declaringaccount1 , account2 andaccount3hasbeenused.

A text enclosedby thebrackets � and � is acomment.4

Stateand statetransitions

Thestateof an objectat agivenpoint in time is thevalueof its attributes,andexecutionof actionsmaychangethestateof anobject.Thestateof a programexecutionat a givenpoint in time is theobjectsexisting at thatpoint in timeandtheir states.

In Figure3.2, thestateof theexecutionof theprogramfrom Figure3.1 isshown. Thecomments{L1} , {L2} and{L3} indicatethreepointscorrespond-ing to thestatesshown in thefigure.At {L1} thevalueof all integerobjectsis0 (zero).(All integerobjectswill initially have thevalue0.) At {L2} thestatediagramshows thatvalueshavebeendepositedin thethreeaccounts.Finally,at {L3} thefinal stateof theprogramexecutionis shown.

3.1.1 Summary

We cannow summarizethesyntacticelementsfor describingobjectsandpat-terns.

3The Mjølner BETA Systemmay be usedfor this. Seethe relevant manualsfor furtherinformation.

4Notethat � and � cannotbeusedin theMjølner BETA System.Instead,(* and*) mustbeused.

Page 39: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

28 OBJECTSAND PATTERNS

(# Account:(# balance: @integer;

Deposit:(# amount: @integerenter amountdo balance+amount->ba lan ceexit balance#);

Withdraw:(# amount: @integerenter amountdo balance-amount->ba lan ceexit balance#);

#);account1, account2, account3: @Account;K1,K2,K3: @integer;

do {L1}100->&account1.Depos it ;200->&account2.Depos it ;300->&account3.Depos it ;{L2}150->&account1.Depos it ->K 1;90->&account3.Withdr aw->K 3;90->&account2.Deposi t- >K2;80->&account3.Withdr aw->K 3;{L3}

#)

Figure 3.1 Accountprogram.

Object-descriptor

Thesyntacticelementfor describinganobjectis calledanobject-descriptor,andhastheform:

(# Decl1; Decl2; ...; Declnenter Indo Impexit Out#)

Theelementsof anobject-descriptorhave themeanings:

Page 40: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.1 OVERVIEW 29

K1: 0K2: 0K3: 0

account3:

balance: 0

account2:

balance: 0

account1:

balance: 0

At L3:

At L2:

At L1:

K1: 250K2: 290K3: 130

account3:

balance: 130

account2:

balance: 290

account1:

balance: 250

K1: 0K2: 0K3: 0

account3:

balance: 300

account2:

balance: 200

account1:

balance: 100

Figure 3.2 Snapshotsof statesduringexecutionof theaccountprogram.

� Decl1; Decl2; ... ;Decln is a list of attribute declarationsthat de-scribestheattribute-partof theobject.Thepossiblekindsof attributesarefurtherdescribedbelow.

� In is a descriptionof theenter-part of theobject.Theenter-part is a list ofinput parameterswhichmaybeenteredprior to executionof theobject.

� Imp is thedo-partof theobject.Thedo-partis animperative thatdescribesthe actionsto be performedwhenthe object is executed. An objectmay,for instance,be executedas a procedure,a coroutine,or as a concurrentprocess.In Chapters13–15,theuseof objectsascoroutinesandconcurrentprocessesis described.

� Out is a descriptionof theexit-part of theobject. Theexit-part is a list ofoutputparameters which may be producedasa resultof executionof theobject.

Page 41: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

30 OBJECTSAND PATTERNS

Theenter-, do- andexit-partsaretogethercalledtheaction-partof theobject.An object-descriptormay have additionalparts,which will be introducedinsubsequentchapters.

Theobject-descriptoris thebasicsyntacticconstructin BETA. It maybeusedto describea patternlike Account , and it may be usedto describeasingleobject like myAccount . An object-descriptoris often part of a largerdescription,andaBETA programis anobject-descriptor. Chapter17describeshow a large numberof object-descriptorsmay be combinedinto a completeprogramthatcanbecompiledandexecuted.

Singular objects

A singularobjectmaybedescribeddirectlyusinganobject-descriptor:

S: @(# Decl1; Decl2; ...; Declnenter Indo Impexit Out#)

TheobjectmyAccount describedatthebeginningof thischapteris anexampleof asingularobject.

Pattern declaration

In BETA, a conceptis representedby a pattern, a patternbeingdefinedbyassociatinganamewith anobject-descriptor:

P: (# Decl1; Decl2; ...; Declnenter Indo Impexit Out#)

Patternsserve as templatesfor generatingobjects(instances). The objectsgeneratedasinstancesof P will all have thesamestructure, i.e. thesamesetof attributes,thesameenter-part,thesamedo-partandthesameexit-part.

Theintensionof theconceptbeingmodeledis givenby theobjectdescrip-tor, while theobjectsthataregeneratedaccordingto this descriptorconstitutetheextension.Thepatternnameis partof thedesignationof theconcept.Bymeansof virtual patterns(seeChapters7 and9) andrenaming,thepatternmayalsobedesignatedby othernames.

Pattern-definedobjects

An instanceof apatternmaybedescribedasfollows:

aP: @P

Page 42: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.2 REFERENCEATTRIBUTES 31

3.2 Referenceattrib utes

The attribute balance of Account is anexampleof a referenceattribute. Areferencedenotesan object, and may be either dynamicor static. A staticreferenceconstantlydenotesthe sameobject,whereasa dynamicreferenceis a variablewhich maydenotedifferentobjects.The balance attribute is astaticreference.

3.2.1 Static references

A staticreferenceis declaredin thefollowing way:

X: @T

whereX is the nameof the referenceandT is a pattern. An instanceof T isgeneratedaspartof thegenerationof theobjectcontainingthedeclaration:thestaticreferenceX will constantlydenotethis T-object.An objectgeneratedinthis way is calleda staticobject, or alsoa part-object, sinceit is a permanentpartof theobjectcontainingthedeclaration.

A singularstatic/part-objectis declaredin thefollowing way:

Y: @(# ... #)

Staticobjectsareusefulfor modelingparthierarchies,i.e. objectswhich con-sistof part-objects.

The following exampledescribesobjectsthat representpoints(e.g. on ascreen).Suchobjectsmayhave two integer attributes:

Point: (# x,y: @integer #)

The Point patternhas empty enter-, do- and exit-parts and a single dec-laration that usesthe predefinedinteger pattern. Given this pattern,twoPoint- objectsmaybegeneratedby thefollowing attributedeclaration:

P1,P2: @Point

ThePoint patternmayin turn beusedto describeattributesof otherobjects.Considerthefollowing patterndeclaration:

Rectangle: (# UpperLeft, LowerRight: @Point #)

Thegenerationof aninstanceof theRectangle patternimpliesthegenerationof two instancesof the Point pattern,onedenotedby UpperLeft andoneby LowerRight . The two Point instanceswill be a permanentpart of thisRectangle object.Figure3.3 illustratesa Rectangle object.

Page 43: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

32 OBJECTSAND PATTERNS

LowerLeft

UpperLeft x

x

y

2

2

1

1

Rectangle

y

Figure 3.3 Diagrammaticrepresentationof a Rectangle object .

3.2.2 Dynamic references

A staticreferenceis constantsinceit alwaysdenotesthesamestaticobject.Itis necessaryto be ableto modelthat an objectmay have referencesto otherobjectswhich arenot partof itself. In addition,it mustbepossibleto modelthat suchreferencesarevariablein the sensethat they may denotedifferentobjectsat differentpointsin time. Both maybedoneby meansof a dynamicreference(or variablereference), asdeclaredin thefollowing way:

A: ˆT

whereA is the nameof the referenceand T is a patternname. A dynamicreferencemayat differentpointsin time denotedifferentobjects.Initially, itdenotesNONE, which represents‘no object.’

Considerthetwo attributes:

A1,A2: ˆAccount

A1 andA2 aredynamicreferenceswhichmaydenoteinstancesof theAccountpattern.A dynamicreferencemaybe givena valueby meansof a referenceassignment. Considerthestaticreference:

A3: @Account

A referenceassignmentof theform:

A3[]->A1[]

implies that the objectdenotedby A3 will alsobe denotedby A1. A similarassignment:

A1[]->A2[]

Page 44: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.2 REFERENCEATTRIBUTES 33

R3

R1

R2

Account

Figure3.4 Illustrationof dynamicreferences.

impliesthat theobjectdenotedby A1 is alsodenotedby A2. After this A1, A2andA3 will all referto thesameobject,illustratedin Figure3.4.

A dynamicreferencewill initially have thevalueNONE, which meansthatit refersto noobject. A dynamicreferencemayalsoexplicitly beassignedthevalueNONE:

NONE->A1[]

Sincea NONEreferencerefersto no object, it hasno meaningto attempttoaccessan objectusinga NONEreference.If A1 hasthe valueNONE, thenanevaluationof theform:

120->&A1.Deposit

is illegal,andexecutionof theprogramis terminated.5

3.2.3 Dynamic generationof objects

It is possibleto createobjectsdynamicallyby the executionof actions. Thefollowing evaluationcreatesaninstanceof theAccount pattern,andtheresultof theevaluationis a referenceto thenewly createdobject:

&Account[]

As for procedureinvocation,thesymbol& meansnew. Thesymbol[] meansthata referenceto theobjectis returnedastheresultof theevaluation.

A dynamicgenerationmaybepartof a referenceassignment:5This is anexampleof a run-timeerror.

Page 45: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

34 OBJECTSAND PATTERNS

&Account[]->A1[]

Theresultof this assignmentevaluationis thata new instanceof Account iscreatedanda referenceto thisnew objectis assignedto A1.

The differencebetween&P and &P[] is very important: the expression&P means‘generatea new instanceof P andexecuteit’; theexpression&P[]means‘generateanew instanceof P withoutexecutingit andreturnareferenceto thenew object.’ This is discussedfurther later. An objectgeneratedin oneof thesewaysis calledadynamicobject.

Dynamicgenerationof objectsis neededto describesystemswherenewobjectsare generatedduring programexecution,as is often the casewhenmodelingreal life phenomena.Froma technicalpoint of view, recursive pro-ceduresandrecursive datastructuresgive rise to the dynamicgenerationofobjects.

3.2.4 Example of usingdynamic references

In a bankingsystem,eachaccountshouldhave anidentificationof theownerof the account. For this reasonwe add an owner attribute to the Accountpattern.Theownershouldnot bea partof theaccountsinceseveralaccountsmayhavethesameowner. Wethereforerepresenttheownerof anaccountasadynamicreferenceto anobjectrepresentingtheowner. Considerthefollowingreviseddescriptionof Account :

Account:(# owner: ˆCustomer;

balance: ... ;Deposit: ... ;Withdraw: ... ;

#);

Owner is a dynamicreferenceto an instanceof the Customer pattern. In-stancesof theCustomer patternhaveattributesrepresentingvariouspropertiesof acustomersuchasnameandaddress:

Customer:(# name: ...;

address: ...;#)

We shallnotgo into Customer in furtherdetail.The following objectgeneratestwo customersand threeaccounts.Two

of the accountshave the sameowner. The resultingobjectsaredepictedinFigure3.5:

Page 46: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.2 REFERENCEATTRIBUTES 35

(# A1: ˆAccount;C1: ˆCustomer;A2: ˆAccount;C2: ˆCustomer;A3: ˆAccount;

do &Customer[]->C1[]; &Customer[]->C2[];&Account[]->A1[]; C1[]->A1.owner[];&Account[]->A2[]; C1[]->A2.owner[];&Account[]->A3[]; C2[]->A3.owner[];

#)

3.2.5 Qualified referencesand remoteaccess

A referenceis qualified(typed)by meansof apatternname.Thequalificationof a referencerestrictsthesetof objectsthatmaybedenotedby thereference.A referencedeclaredas:

R1: ˆRectangle

mayonly denoteinstancesof theRectangle pattern.Rectangle is calledthequalificationor thequalifyingpatternof R1.

Attributesin objectsmaybedenotedby remoteaccess, whichhastheform:

reference.attribute

The qualificationof a referencedetermineswhich attributesmay be denotedby remoteaccess. For a referencelike R1, the attributes UpperLeft andLowerRight maybedenoted:

R1.Upperleft R1.LowerRight

SinceR1 is qualifiedby Rectangle , R1 cannotbeassigneda referenceto aninstanceof thePoint pattern.Also, it is not possibleto refer to non-existingattributes. Illegal assignmentsandaccessof non-existing attributesgive riseto many errorsin languageswithout qualifiedreferences.In a typedlanguagelike BETA, sucherrorsmay be detectedby the compiler. The disadvantageof qualifiedreferencesis lessflexibility for theprogrammer. In Smalltalkandmost object-orientedextensionsof Lisp, sucherrorsare first caughtat run-time. However, whenconstructingindustrialsoftware,it is a greatadvantageto have thecompilercatchasmany errorsaspossible.Notethatastaticrefer-encewill automaticallydenoteaninstanceof thequalifying pattern.

Page 47: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

36 OBJECTSAND PATTERNS

a1

a2

a3

c1

c2

Deposit

Withdraw

Owner

balance

Account

Deposit

Withdraw

Owner

balance

Accountname

address

Customer

name

address

Customer

Deposit

Withdraw

Owner

balance

Account

Figure3.5 Accountobjectsandcustomerobjects.

3.3 Pattern attrib utes

Thedeclarationof apatternattributehastheform:

P: (# ... #)

Themeaningof a patternattributehasbeendescribedin Section3.1. Severalexamplesof patternattributeshave alreadybeenshown, including Account ,Deposit andWithdraw .

Page 48: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.3 PATTERN ATTRIBUTES 37

In thenext versionof thePoint pattern,a patternattributeMove hasbeenadded.Move describeshow Point objectsmaybemovedaround:

Point:(# x,y: @integer; {two reference attributes}

Move: {a pattern attribute}(# dx,dy: @integerenter(dx,dy)do x+dx->x;

y+dy->y#)

#)

A Point objectP1 may be ‘moved’ by executingan instanceof P1’s Move-attribute:

(11,22)->&P1.Move

whichdescribesanexecutionof P1.Move with parameters(11,22) . A Pointobjecthastwo referenceattributesandapatternattribute,but noenter-, do-orexit-parts.

Thedo-partis invokedby invoking a patternnameasin &P1.Move, whichinvokesthe do-partof the Move- patternin P1 asa procedure.&P1.Move de-scribesthat an instanceof the Move- patternwill be created,andcausesthedo-partof this instanceto beexecuted.Thesymbol& readsnew.

It is importantthat eachinstanceof Point hasits own setof attributes.Figure3.6 representsthe objectsP1 andP2. The Move attributesdenoteob-jectsrepresentingthestructureof patternMove. Sucha structure objecthasareferencepointingbackto theobjectof which thepatternis anattribute.Thisreferenceis calledthe origin of the pattern. Eachinstanceof P1.Move willhaveacopy of theorigin referenceof thestructureobjectcorrespondingto theMove attributeof P1, andthesameis truefor instancesof P2.Move . Figure3.7shows instancesof P1.Move andP2.Move . Noticethedifferencebetweenthestructureobjectsin Figure3.6describingthepattern attrib utesMove andtheobjectsin Figure3.7representinginstancesof Move.

The origin referenceis usedwhen an object-descriptorrefersto a non-local (global)attribute. In Move theglobalattributesx andy arereferred.Anevaluationlike:

x+dx->x

is theninterpretedas:

origin.x+dx->origin.x

Page 49: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

38 OBJECTSAND PATTERNS

P1 P2

Move

x

Point

y

Move

x

Point

y

111

222

333

444

struc (# ... #)

Move

origin

Move Move

struc (# ... #)

Move

origin

Figure3.6 Diagrammaticrepresentationof Point objects.

P1 P2

Move

x

Point

y

Move

x

Point

y

111

222

333

444

Move Move

Move

origin

dx

dy

1

2

Move

origin

dx

dy

1

2

Figure3.7 Point objectsandMove objects.

If P1.Move is executed,the origin referenceof the Move objectwill refer toP1. If P2.Move is executed,theorigin referenceof theMove objectwill referto P2.

Page 50: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.3 PATTERN ATTRIBUTES 39

3.3.1 Self-reference

It is often useful to be able to refer directly to an enclosingobject. This ispossibleusingtheconstruct:

this(P)

which is legal in the object-descriptorfor P, i.e. this(P) may only appearinsidea P pattern:

P: (# ... this(P) ... #)

this(P) is anexplicit namefor theenclosingP object.ThepatternPoint canbedescribedusingthis(P) in thefollowing way:

Point:(# x,y: @integer; {two reference attributes}

Move: {a pattern attribute}(# dx,dy: @integerenter(dx,dy)do this(Point).x+dx->this(Point).x;

this(Point).y+dy->this(Point).y#)

#)

Explict useof this(P) maymake it easierto reada programwhenreferringto globalnames.

Theconstructthis(P) is oftenusedto obtaina referenceto anenclosingP object:

this(P)[]

We shallseeexamplesof this later.

3.3.2 Procedure, function and classpatterns

Theaboveexampleshaveshown two fundamentallydifferentwaysof usingapattern:(1) The Account patternhasbeenusedasa templatefor generatingobjectsthathaveastatewhichchangesovertime; (2) theDeposit patternhasbeenusedasa templatefor generatinganaction-sequence.

In general,a patternis a generalizationof abstractionmechanismssuchasclass, type, procedure, function, etc. The fact thatBETA hasonly oneab-stractionmechanismdoesnotmeanthatit is notusefulto distinguishbetweendifferentkinds of patterns. In the following we shall refer to conceptslikeclasspattern, procedurepatternandfunctionpatternfor patternsthatareused

Page 51: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

40 OBJECTSAND PATTERNS

asclasses,proceduresandfunctions,respectively. In laterchapterssomead-ditional conceptswill be introduced.Note,however, that technicallythereisno distinctionin BETA betweensuchpatternkinds. In therestof this sectionweshallelaboratefurtheronsomeof themostusefulpatternkinds.

Procedure patterns

The Deposit patternis usedfor generatingan action-sequence.To repre-senttemporarystateinformationduring this action-sequence,an instanceofDeposit is generated.Sucha patternis usuallycalleda procedure. Assumethat Deposit is a traditional (Pascal)procedure.A procedureinvocationofDeposit givesrise to the generationof an activation record,which is usedfor storingparametersandlocal variablesof the invocation. The instanceofthe BETA patternDeposit beinggeneratedplays the role of the procedureactivation.

Froma modelingpoint of view, theDeposit procedureandtheDepositpatternareusedto generateaction-sequences.The activation recordandtheobjectareonly generatedto representtemporarystateinformation.However,from animplementationpointof view theseobjectsmustbeconsidered,sincethey takeup spaceduringtheprogramexecution.

TheDeposit patternis usedasa procedurein thefollowing way:

500->&account1.Deposit->newBalanc e

As describedabove, an instanceof account1.Deposit will be createdandexecuted.

Sincepatternsmay be usedasprocedures,it is possibleto expresspro-ceduralprogrammingin BETA asin Pascal,Modula-2,Ada or C. This styleof programmingis not recommendedin general,but often a minor part of asystemmay be expressedmoreelegantly by usingproceduralprogrammingratherthanobject-orientedprogramming.

Function patterns

Patternsmayalsobeusedasfunctions:theInterest patternis anexampleofa functionpattern.Interest computestheinterestona givensumof money:

Interest:(# sum,interestRate,res: @integerenter(sum,interestRate)do (sum*interestRate) div 100->resexit res#)

Interest maybeusedin thefollowing way:

Page 52: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.3 PATTERN ATTRIBUTES 41

(1100,3)->&Interest->V

Thevalueof V is then3% of 1100.What is actually meantby a function pattern? Here a function pattern

meansa patternintendedfor computinga valueon thebasisof a setof inputparameters.Theinput valuesareenteredthroughtheenter-part,andthecom-putedvalueis returnedvia theexit-part. Thecomputedvaluedependssolelyon theinput values.In addition,thecomputationof thevaluedoesnotchangethestateof any otherobject(therearenoside-effects).

Considerinsteadthe following pattern,which computesthe sum of thebalancesof threeaccounts:

TotalBalance:(# sum: @integerdo account1.balance->sum;

sum+account2.balance->sum;sum+account3.balance->sum;

exit sum#)

Herethevaluecomputedby TotalBalance dependsonthestateof theobjectsaccount1 , account2 and account3 , i.e. different calls of TotalBalancemayreturndifferentvalues.

Classpatterns

The Account patternis usedasa templatefor generatingobjectsthathave astatewhich changesover time. An instanceof Account modelsa real phys-ical object in the form of a bankaccount.A patterndescribingsuchobjectshastraditionally beencalleda class. Account is thusan exampleof a classpattern.

Figure 3.8 shows anotherexampleof a classpatternwhich describesalinked list of integers. Elementsmay be insertedin the list by meansof theprocedurepatternInsert . Thefollowing objectcreatesalist of four numbers:

(# head: @Linkdo 1 ->head.Insert;

2 ->head.Insert;6 ->head.Insert;24->head.Insert;{head = (0 24 6 2 1) }

#)

Theobjectdenotedby Head is just usedfor representingtheheadof the list,i.e. it is notpartof thelist.

Page 53: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

42 OBJECTSAND PATTERNS

Link: {Link describes a linked list}(# succ: ˆLink; {tail of this Link}

elm: @integer; {content element of this Link}

Insert: {Insert an element after this Link}(# E: @integer; R: ˆLink;enter Edo &Link[]->R[]; {R denotes a new instance of Link}

E->R.elm; {E=R.elm}succ[]->R.succ[]; {tail of this Link = tail of R}R[]->succ[]; {R=tail of this Link}

#)#)

Figure3.8 Classpatterndescribinga recursivedatastructure.

Someclasspatternslike Rectangle only includereferenceattributes. Apatternusedin thisway is similar to a recordtypein Pascal,i.e.apatternmayalsobeusedasa recordtype.

3.3.3 Basicpatterns

A numberof predefinedbasicpatternsfor commonlyuseddatatypessuchasinteger , boolean , char andreal andtheir operationsareavailable.

For the integer pattern,the functionalpatterns+, -, *, div andmodareavailable,correspondingto theusualarithmeticfunctions. Div is integerdivisionwith truncation;Mod is themodulusfunctioncomputingtheremainderof an integerdivision. Considerthe following declarationof threeinteger -objects:

I,J,K: @integer

Thestandardinfix notationfor integer expressionscanbeused:

1+I->I; (I*J)+12->K

In principle,it correspondsto thefollowing evaluationusingfunctioncalls:

(1,I)->+->I; ((I,J)->*,12)->+->K

It is, however, not possibleto usethe above function call syntax. Only theinfix notationcanbeused.

Page 54: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.3 PATTERN ATTRIBUTES 43

For the real pattern,thearithmeticoperations+, - , * and / aredefined.For theboolean pattern,thefunctionalpatternsand , or andnot aredefined.In addition, the patternsfalse and true describeobjectsrepresentingthebooleanvaluesfalseandtrue.

The char patternis a representationof the ASCII characterset. Eachcharacterin the ASCII characterset hasan associatedvalue in the interval�0� 255� . TheprintableASCII charactersmaybedenotedin thefollowing way:

’a’ ’b’ ... ’0’ ’1’ ... ’!’ ’@’ ...

The value of a char object is the integer correspondingto the char in theASCII characterset,meaningthat it is possibleto performintegeroperationson chars.Theevaluation:

’a’+1->b

will assigntheASCII valueof ’a’ plusoneto thevariableb. SincetheASCIIvalueof ’a’ is 97 andthe ASCII valueof ’b’ is 98, b will have the ASCIIvalueof ’b’ .

Thereal patternis a representationof floatingpoint numbers.6

Relational operators The functional patterns=, <>, <, <=, > and >=correspondingto thestandardrelationalfunctionsequal,not equal,lessthan,lessthanor equal,greaterthanandgreaterthanor equalareavailablefor inte-ger, boolean,charandrealobjects.For boolean,the false patterndescribesobjectswhich arelessthanandnot equalto objectsdescribedby True . Forcharobjects,theASCII orderingis used.

Initial values Instancesof basicpatternswill haveadefault value:Integerobjectswill havethevalue0; char objectswill havethevalue0 correspondingto the null character;boolean objectswill have thevaluefalse ; andrealobjectswill have thevalue0.0 .

Restrictions In theMjølnerBETA Systemthereareafew pragmaticrestric-tions on the usageof basicpatterns. It is not possibleto declaredynamicreferencesto instancesof suchpatterns.Also, a basicpatterncannotbeusedas a super-pattern(seeChapter 6). BETA is a very generallanguage,andsometimesthis generalitymakesit hardto obtainanefficient implementation.Theabove restrictionsareimposedfor efficiency reasons.Thereis no logicalmotivationfor theserestrictions.

6In thecurrentimplementationsof the Mjølner BETA System,a 64-bit representationoffloatingnumbersis used.For detailsconsulttheMjølnerBETA Systemmanuals.

Page 55: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

44 OBJECTSAND PATTERNS

3.4 Exercises

(1) Use the Mjølner BETA Systemto executethe accountprogramin Fig-ure3.1.

(2) Definethename andaddress attributesof the Customer patternin Sec-tion 3.2.4. An addressshouldconsistof street,streetnumber, city, zipcodeandcountry.

(3) Define patternsrepresentinga point, line, segment,polygon, rectangle,squareandrhombus. A segmentis a list of lines wheretheendpoint ofoneline is thestartingpoint of thenext line.

It shouldbepossibleto createobjectsof thesepatterns,move theobjects,changeoneof the coordinatesof a point, changethe start(or end)pointof a line, changethestart(or end)pointof a line in asegmentor polygon,adda new line to a segment,andadda segmentto a segment(considerwhatthis couldmean).

3.5 Notes

A patternis a unificationof abstractionmechanismslike class,type, proce-dure,function,genericpackage,etc.It is afurthergeneralizationof theSimulaclassconstruct.

Patternsmayalsobecomparedto classesin Smalltalk. Patternattributesof a patterncorrespondto interfaceoperationsin Smalltalkclasses,andref-erenceattributescorrespondto instancevariables. The do-partof an objecthasno counterpartin Smalltalk,andis usedwhentheobjectis executedasaprocedure,coroutineor process.Comparedto Smalltalk,thedo-partof anob-ject representsa very importantextensionof thenotionof objectsthatallowspatternsto be executedasprocedures,and to be usedin modelingongoingprocessesandin systemsimulation.

A dynamicreferenceis similar to a referencein Simulaandan instancevariablein Smalltalk.It resemblesSimulain thesensethata BETA referenceis qualified.Instancevariablesarenotqualifiedin Smalltalk.Theadvantageofqualifiedreferencesis (1) thecompilermaydetectillegal accessof attributes,(2) the compilermay generatemoreefficient code,and(3) the qualificationimproves the readabilityof the code. The price for this is, of course,lessflexibility for theprogrammer. For implementingindustrialsoftware,a typedlanguagelikeBETA will leadto morerobustandsafeprograms.

Generationof dynamicobjectswith subsequentassignmentof the refer-enceto a dynamicreferencevariable&P[]->R[] correspondsto R � P Newin Smalltalk.

The framework for BETA presentedin Chapter2 makesa distinctionbe-tweenphenomenaandconcepts,andthis is reflectedin the language:objects

Page 56: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

3.5 NOTES 45

modelphenomenaandpatternsmodelconcepts– a patternis not an object.In contrastto thisdistinctionbetweenobjectsandpatterns,Smalltalk-like lan-guagestreatclassesasobjects.Conceptsarethusboth phenomenaandtheyare usedto classifyphenomena.In the BETA framework, patternsmay betreatedasobjects,but thatis in theprogrammingprocess. Theobjectsmanip-ulatedin a programmingenvironmentwill befragments(e.g. patterns)of theprogrambeingdeveloped.

Thereareobject-orientedlanguagesthatdo not havea notioncorrespond-ing to patterns;suchlanguagesarecalledclasslessor prototype-based. Insteadof generatingobjectsasinstancesof patterns(classes),anobjectis generatedasacloneof anotherobject.Theobjectbeingclonedis consideredasaproto-typeto beusedfor generatingsimilar objects.Thegeneratedobjectwill havethesamepropertiesastheobjectfrom which it is generated,but it maymodifysomeof thepropertiesandaddnew ones.The mostwell known exampleofsucha languageis Self(UngarandSmith,1987).

BETA is a languagebelongingto the Algol family with respectto blockstructure,scoperulesandtypechecking.In Algol andSimulaa procedureorblock mayhave local proceduresand/orblocks. With respectto scoperules,BETA also follows the Algol tradition, sinceall namesin textually enclos-ing objectdescriptorsarevisible. In additionto the Algol scoperules,mostlanguagessupportingclasseshave a rule thatprotectscertainattributesof anobject from beingaccessedremotely. In Simula this is handledby the hid-den/protectedmechanism;in Smalltalk,instancevariablescannotbeaccessedfrom outsidethe object. BETA containsno suchprotectionmechanism;in-stead,themodularizationdescribedin Chapter17 is used.

Page 57: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

46 OBJECTSAND PATTERNS

Page 58: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 4

Repetitions

It is possibleto declarea repetitionof staticor dynamicreferences.A repeti-tion of staticreferencesis declaredin thefollowing way:

A: [eval] @P;

A is thenameof arepetitionof staticreferencesandP is apatterndescribingthestaticinstances.eval is anevaluationresultingin anintegernumbercalledtherangeof therepetition.Therangeof a repetitionmaybedenotedby A.range .This repetitiondescribesthefollowing setof staticreferences:

A[1], A[2], ..., A[A.range]

An element in the repetition may be denotedby an expressionA[exp] ,whereexp is an integer evaluationthat mustresult in a valuein the interval[1,A.range] .

The examplein Figure4.1 illustratesthe useof a repetitionof staticref-erences.A repetitionof integershasbeenaddedto theAccount pattern.Therepetitiontransactions keepstrackof thesequenceof transactionsthathavebeenmadeon the account.When50 transactionshave beenmade,1 a state-mentof thetransactionsis sentto thecustomer(only indicatedby acomment),therepetitionis cleared,andtherecordingof transactionsis begunagain.

A repetitionmayalsoconsistof dynamicreferences:

A: [eval] ˆP

Hereeachelementin therepetitionis adynamicreference.The example in Figure 4.2 illustrates the use of a repetition of dy-

namic references.The object BankSystem includestwo repetitionsof dy-namic referencesfor keepingtrack of all accountsand customershandled

1For adescriptionof the if -imperativeseeChapter5.

47

Page 59: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

48 REPETITIONS

Account:(# ...

transactions: [50] @integer; Top: @integer;

Deposit:(# amount: @integerenter amountdo balance+amount->ba lan ce;

amount->&SaveTrans act ionexit balance#);

Withdraw:(# amount: @integerenter amountdo balance-amount->ba lan ce;

-amount->&SaveTran sac tio nexit balance#);

SaveTransaction:(# amount: @integerenter amountdo (if (top+1->top)>transac ti ons .ra nge // true then

{Send statement of transactions to the customer}1->top

if);amount->transactio ns[ top ]

#)#)

Figure4.1 Recordingof transactions.

by the bank. The bankmay have at most200 accountsand100 customers.The integer objectnoOfAccounts keepstrack of the currentnumberof ex-isting accounts. The referencesAccountFile[1] , AccountFile[2] , ...,AccountFile[noOfAccounts] arethecurrentlyexisting accounts.Thepat-tern NewAccount generatesa new accountandaddsit to thefile. Customersarehandledin asimilarway.

If aCustomer is a referenceto a customer, then a new accountfor thiscustomermaybegeneratedusingNewAccount , asin:

aCustomer[]-> BankSystem.NewAccount->anAccount[]

ThereferenceanAccount will thenreferto thenew account.

Page 60: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

4.1 REALLOCATION, ASSIGNMENTAND SLICE 49

BankSystem: @(# Account: (# ... #);

Customer: (# ... #);

AccountFile: [200] ˆAccount;noOfAccounts: @integer;

CustomerFile: [100] ˆCustomer;noOfCustomers: @integer;

NewAccount:(# C: ˆCustomer; rA: ˆAccountenter C[]do noOfAccounts+1->noO fA cco unt s;

&Account[]->rA[]->A cc oun tFi le[ noOfAcco unt s] [];C[]->AccountFile[no Of Accoun ts] .o wner[]

exit rA[]#)

NewCustomer: (# ... #)#)

Figure4.2 Bankingsystem.

4.1 Reallocation,assignmentand slice

Thebankingsystemin Figure4.2mayholdatmost200accountsand100cus-tomers. In practice,it is not acceptablethat suchlimitations arehard-codedinto a program:it mustbepossibleto dynamicallyexpandthesizeof a repe-tition. In BETA it is possibleto extendthe rangeof a repetition. Consideradeclaration:

R: [16] @integer

Executionof theimperative

10->R.extend

extendsthe sizeof R by 10 elements.SinceR.range=16 beforethe assign-ment,R.range=26 aftertheassignment.TheelementsR[1] , R[2] , .... R[16]have thesamevaluesasbeforetheassignment.TheelementsR[17] , R[18] ,... R[26] have thedefault valuefor integer objects(which is zero).

It is alsopossibleto make a completenew allocationof a repetition.Exe-cutionof

Page 61: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

50 REPETITIONS

25->R.new

will allocatea new repetitionof 25elements.Thepreviouselementsareinac-cessible;thenew elementswill have thedefault valueof theelementpatterninteger .

Theextend andnew operationsaredefinedfor all repetitions.Assignmentis definedfor repetitionsin general.Considerdeclarations:

R1: [18] @integer;R2: [12] @integer

An assignment

R1->R2

hasthefollowing effect:

R1.range->R2.new;R1[1]->R2[1]; R1[2]->R2[2]; ...;R1[R1.range]->R2[R2.range]

Or expressedusingthe for -imperative:2

R1.range->R2.new;(for i: R1.range repeat R1[i]->R2[i] for)

Since the rangeof a repetitionmay be changedby using assignment,newandextend , oneshouldalwaysusethe range attribute to refer to the range.Insteadof

(for i: 12 repeat sum+R2[i]->R2[i] for)

it is usuallybetterto use:

(for i: R2.range repeat sum+R2[i]->R2[i] for)

It is possibleto assignpart of a repetitionto anotherrepetitionby using arepetitionslice, which hastheform:

R2[3:9]

Suchaslicecanbeusedin anassignmentlike:

R2[3:9]->R1

which is similar to R2->R1 exceptthatthesourcerepetitiononly has9-3+1=7elements.Theboundsin aslicecanbearbitraryevaluationsyieldinganintegervalue:

R2[e1:e2]->R1

which means

e2-e1+1->R1.new;R2[e1]->R1[1]; R2[e1+1]->R1[2]; ...; R2[e2]->R1[R1.range]

2SeeChapter5.

Page 62: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

4.2 THE TEXT PATTERN 51

4.2 The text pattern

A predefinedpatternfor representinga text conceptis available,thoughit isnot a basicpatternlike integer , boolean , char and real . The restrictionsfor thebasicpatternsmentionedin Section3.3.3donotapplyto text objects.It is thuspossibleto createdynamicreferencesto text objectsandto usethetext patternasa super-pattern(seeChapter6). Thereare,however, a fewbuilt-in languagefeaturesthatarespecialfor the text pattern.Thefollowingis anexampleof usingthe text pattern:

(# T1,T2: @text; T3: ˆtextdo ’Hello’->T1; ’World’->T2; T2[]->T1.append;

&text[]->T3[]; T1->T3;#)

A text objectmay be generatedandusedasany otherobject. As may beseen,a text objectmaybeassigneda text constant(like ’Hello’ ), andonetext objectmaybeassignedto anothertext object(asin T1->T3 ). A textobjecthasa numberof attributes(like append ) which arenot predefined,butarepartof thebasiclibrary definedfor theMjølner BETA System.

Basically, a text objectis representedby a repetitionof char objects:

text:(# R: [16] @char;

...#)

It is possibleto assigna text constantto acharrepetition:

’Hello’->R

Theeffectof this is that:

R[1]=’H’, R[2]=’e’, R[3]=’l’, R[4]=’l’, R[5]=’o’

andthat:

R.range = 5

The assignmenthasthe effect that the previous contentof the repetitionisoverwritten.

A text objectcanhold anarbitrarynumberof char objects.This is im-plementedby meansof R.extend whenever thesizeof the text objectneedsto beenlarged.

Page 63: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

52 REPETITIONS

4.3 Exercises

You mayhave to readChapter5 to solve theexercisesbelow.

(1) Completethe text patternby giving a completeimplementationanddefining a suitableset of operations. A text object shouldbe able toholda text of anarbitrarylength.

Discussthe strategy for extendingthe sizeof the text. Shoulda text -objectbe extendedwith a fixed sizeevery time, n%of its currentsizeordoubleits size?

(2) Completethebankingsystemin Figure4.2.

Use the Customer patterndevelopedin Exercise2 in Chapter3. Addprocedurepatternsfor removing accountsandcustomers.

Changethe recordingof transactionsto keeptrackof the latest50 trans-actions.For each50 transactionssendout astatementto thecustomer.

Modify theAccount patternsuchthatanaccountmayhave severalown-ers.

The banksystemshouldnot be restrictedto handlea limited numberofcustomersandaccounts.

4.4 Notes

Therepetitionconstruct(oftencalledanarray) hasbeenknown sincetheearlydaysof programminglanguages,and is presentin languagessuchasFOR-TRAN andAlgol 60. Algol 60 introducedthenotionof dynamicarrayswherethe size of the array is computedat run-time. After an array is createditssizecannotbe changed.Oneof thesuccessorsto Algol 60, Pascal,imposedthelimitation on arraysthat their sizemustbeknown at compile-time,whichmeansthat only constantsmay be usedto specify the sizeof Pascalarrays.Themotivationfor this restrictionwasefficeincy.

Thepossibilityof extendingthesizeof anarrayafterit hasbeencreatedisknown from a numberof otherlanguages,includingAlgol 68. Extendingthesizeof anarrayis anexpensive operation,sinceit usuallyimplies allocationof anew arrayobjectandcopying of theold valuesto thenew area.

Page 64: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 5

Imperati ves

Thedo-partof anobjectis a sequenceof imperativesthatdescribesactionstobeexecuted.Until now wehaveseenvariousexamplesof imperatives:

x+dx->x; {assignment}(11,22)->&P1.Move; {procedure invocation}R1[]->R2[]; {reference assignment}&Rectangle[]->R1[]; {dynamic generation and}

{reference assignment}

The first four imperativesareexamplesof the evaluationimperative, whichwill befurtherdescribedin thenext sub-section.In addition,BETA hasa fewimperativesfor controlling the flow of executions,calledcontrol structures,which will alsobedescribedbelow.

5.1 Intr oduction to evaluations

The basicmechanismfor specifyingsequencesof object executionstepsiscalledanevaluation. An evaluationis animperativethatmaycausechangesinstateand/orproducea valuewhenit is executed.Thenotionof anevaluationprovidesa unified approachto assignment,function-callandprocedure-call.Examplesof evaluationsare:

(11,22)->&P1.Move;x+dx->x

Theevaluation:

x+dx->x

specifiesanordinaryassignment(theassignmentof x+dx to x). An evaluationmayspecifymultipleassignment, asin:

53

Page 65: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

54 IMPERATIVES

(#Power: {Compute Xˆn where n>0}

(# X,Y: @real; n: @integer;enter(X,n)do 1->Y;

(for inx: n repeat Y*X->Y for)exit Y#);

Reciproc: {Compute (Q,1/Q)}(# Q,R: @realenter Qdo (if Q // 0 then 0->R

else (1 div Q)->Rif)

exit(Q,R)#);

A,B: @realdo (3.14,2)->&Power->&R ec ipr oc- >(A ,B );

{A=3.14*3.14, B=1/A}#)

Figure5.1 Exampleof usingpatternsasprocedures/functions.

3->I->J

where3 is assignedto I andthevalueof I is assignedto J . Theevaluation:

(11,22)->&P1.move

specifiesa procedure-call.Thevalue(11,22) is assignedto theenter-partofP1.Move , andP1.Move is thenexecutedwith theseenterparameters.NotethatthepatternP1.Move is invokedasaninstance.

As shown above,anevaluationmayspecifymultipleassignmentof values.Themultiple assignmentform mayalsobeusedto combineexecutionof ob-jects.Considertheexamplein Figure5.1. Theprogramcontainsthedeclara-tion of twopatterns,Power andReciproc , andtwoobjectsof thepatternreal ,A andB. Thedo-partof theprogramconsistsof theevaluation-imperative:

(3.14,2)->&Power->&Reciproc->(A,B )

Page 66: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.2 FOR-IMPERATIVE 55

The executionof this evaluation-imperative takesplaceasfollows: The val-ues 3.14 and 2 are assignedto the input parametersX, n of Power (de-scribedby enter(X,n) ), thedo-partof Power is executed,theoutputparam-eterY of Power (describedby exit Y) is assignedto the input parameterQof Reciproc , the do-partof Reciproc is executed,and finally, the output-parametersQ, R of Reciproc areassignedto A,B .

The do-part of Power consists of two imperatives: an evaluation-imperative assigningY thevalue1; anda for-imperative. The index-variableinx stepsthroughthe values1,2, ... ,n . The do-partof the Reciprocpatternconsistsof anif-imperative.

Notethata function-patternmayreturna list of valueslike theReciprocpattern. The resultof a patternreturninga list may be entereddirectly intoanotherpatternthathasa compatibleenter-part. Assumethat thepatternMaxhasan enter-part consistingof two reals. Reciproc and Max may then becombinedin thefollowing way:

exp->&Reciproc->&Max->M

Thepreviousexampleshaveshown examplesof evaluationsdescribingthegenerationof objectsasinstancesof patterns.It is alsopossibleto usesingularobjectsin theactionpart,asshown in thefollowing example:

(# Y,V,W: @realdo ...;

{Singular object:}(# X: @realdo Y->&Reciproc->(V,W);

(V,3)-> &Power->V;(W,5)-> &Power->W;

#);...

#)

Theactionpartof theabove objectdescriptorincludesa singularobject.Sin-gular objectsin the action part are useful when there is a needfor declar-ing somelocal objects(like X above) which areonly neededfor intermediatecomputations.In general,it is possibleto arbitrarily nestobject-descriptors,includingsingularobjectsandpatterns(seeSection5.9).

5.2 For-imperative

Theiterationcontrolstructureof BETA is calleda for-imperativeandhasthefollowing form:

Page 67: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

56 IMPERATIVES

(for Index: Range repeat Imperative-list for)

where Index is the nameof an integer- objectandRange is an integer -evaluation.Range is evaluatedprior to theexecutionof thefor-imperative,anddeterminesthe numberof timesthat Imperative-list is executed. Indexwill stepthroughthevalues[1, 2, ..., Range] . ThenameIndex is onlyvisible in the Imperative-list . It is not possibleto assignto Index . Thefollowing exampleillustratesthefor-imperative:

(# V: [100] @integerdo (for i: V.range repeat i->V[i] for);

0->sum;(for i: V.range repeat sum+V[i]->sum for)

#)

Thefor-imperativedescribesthattheimperative:

i->V[i]

is executedV.range numberof times,i.e. 100times.Theindex variablei willstepthroughthevalues[1,2,...,100] . Thefor-imperativethusdescribesanexecutionof:

1->V[1];2->V[2];...100->V[100]

Often it is desirableto stepthroughan index setwhich doesnot startwith 1,andwhichuses1 to incrementtheindex variable.An exampleof suchanindexsetis [-4, -2 ,0, 2, 4] . In Chapter6 anexamplewill begivenof how todefinenew controlstructuresusingpatterns.BETA hasonly a few predefinedcontrol structures– the ideais thatmostcontrol structuresshouldbedefinedusingpatterns.

5.3 If-imperati ve

Theselectioncontrolstructureis calledan if-imperativeandhasthefollowingform:

(if E0// E1 then I1// E2 then I2

...// En then Inelse I

if)

Page 68: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.3 IF-IMPERATIVE 57

whereE0, E1, E2, ..., En areevaluationsandI1 , I2 , ..., In andI areimpera-tives. Theelsepart (else I ) is optional. E0 is first evaluated,andthatvalueis testedfor equalitywith E1, E2, ..., En in anarbitraryorder. If E0 � E j thenI j may be selectedfor execution. If oneor morealternativesareselectable,thenoneof theseis chosenrandomly. If no alternative canbe selected,thenthepossibleelsepart is executed;otherwise,theexecutioncontinuesaftertheif-imperative.

In the following examplethe integer object x is testedfor equalitywithsomeintegerevaluations:

(if x// 17 then ...// 33 then ...// y+3 then ...else ...

if);

The next exampleshows how to selecton the basisof a booleanvalue. Thefalsecasemayalsobehandledby anelsepart:

(if (x>0) and (y<0)// True then ...// False then ...

if)

The next exampleshows how to selecton the basisof a numberof booleanconditions:

(if true// (x<0) and (y=0) then ...// (x=0) and (y=0) then ...// x>=0 then ...

if)

It is also possibleto selectby comparingreferences.Assumethat R0, R1,R2 andR3 arereferencesto Point objects.The following if-imperative testswhetheror not R0 denotesthesameobjectasoneof R1, R2 andR3:

(if R0[]// R1[] then ...// R2[] then ...// R3[] then ...

if)

Page 69: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

58 IMPERATIVES

In theabove example,R0 andR1 maydenotedifferentPoint objects,but thex and y attributesof theseobjectsmay still be identical. In this case,thetwo objectshave the samestateor value. In BETA thereis cleardistinctionbetweenreferenceequalityandvalueequality. In theif-imperative above thereferencesaretestedfor referenceequality. It is alsopossibleto testwhetherthetwo point objectsareidenticalwith respectto thevaluesof their attributesx andy . In BETA, valueequality is not just a bit by bit comparisonof thetwo objects;the descriptionof a patternmustexplicitly describehow valueequality is carriedout. Assumingthat this hasbeendone,an if-imperativetestingfor valueequalityof thePoint objectsmaylook asfollows:

(if R0// R1 then ...// R2 then ...// R3 then ...

if)

Hereit is testedwhetheror not thestateof theobjectdenotedby R0 is identicalto thestateof someof theotherobjects.

Note that it is the presenceof the symbol [] which indicatesreferenceequalityinsteadof valueequality. This is thesameusageof [] asfor dynamicgenerationandreferenceassignment(Section3.2.3).

5.4 Labels and jump imperatives

A labeledimperativehasoneof thefollowing forms:

L: Imperative

(L: Imp1; Imp2; ... Impn :L)

whereL is a name.In thefirst case,thescopeof thelabel is the Imperativeto which the label is attached,i.e. L may only be referred to within theImperative . In the secondcase,the scopeof the label is the imperativesImp1; Imp2; ... Impn . Theexecutionof a labeledimperativemaybeter-minatedby executinga leave-or restart-imperativewithin it: if leaveL is ex-ecuted,theexecutioncontinuesafter the imperative labeledby L; if restartLis executed,the executioncontinuesat the imperative labeledby L, i.e. theexecutionof thelabeledimperative is repeated.

Considerthefollowing example:

(L: (if ... if);M: {2}

(for ... repeat

Page 70: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.5 A LARGE EXAMPLE 59

(if ...// ... then leave L// ... then restart M

if)for);

X->Y:L) {1}

An executionof leaveL impliesthatexecutioncontinuesat � 1� . An executionof restartMimpliesthatexecutioncontinuesat � 2� .

5.5 A largeexample

The Register pattern in Figure 5.2 describesa category of objects.EachRegister -objectconsistsof the attributesTable, Top, Init, Has,Insert andRemove. Table is an indexedcollectionof staticreferencesde-noting100 integer- objects.

TheRegister patternmaybeusedasfollows:

(# R: @Registerdo &R.Init;

(for inx: 6 repeatinx*inx->&R.Insert

for);(for elm: 100 repeat

(if (elm->&R.Has) // True then{elm is in R} ...

if)for)#)

Theimperative&R.Init hastheeffectof initializing R. Thenthesquareof thenumbers1-6 areinsertedinto R. Finally, it testswhich integersfrom 1 to 100aremembersof R.

Theoperationsof a Register objectaredefinedby thepatternattributesInit, Has, Insert andRemove. The representationof a Register objectis thereferenceattributesTable andTop. A Register objectshouldonly beaccessedvia its operations.The above descriptionof the Register patterndoesnot preventaccessto therepresentation– mechanismsfor doingthis aredescribedin Chapter17.

5.6 Assignmentand equality

Oneof the fundamentalconceptsin programmingis the distinctionbetweentheaddressof amemorylocationandthecontent(state)of amemorylocation

Page 71: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

60 IMPERATIVES

Register:(# Table: [100] @integer; Top: @integer;

Init: (#do 0->Top #);Has: {Test if Key in Table[1:Top]}

(# Key: @integer; Result: @boolean;enter Keydo False->Result;

Search:(for inx: Top Repeat

(if ((Table[inx]=Key)- >Resul t) // Truethen leave Search

if)for)exit Result#);

Insert: {Insert New in Table}(# New: @integerenter Newdo (if (New->&Has) {Check if New is in Table}

// False then {New is not in Table}Top+1->Top(if (Top<=Table.Range) {Table.Range=100}

// True then New->Table[Top]// False then {Overflow}

if)if)#);Remove: {Remove Key from Table}

(# Key: @integerenter keydo Search:

(for inx: Top repeat(if Table[inx] // Key then

(for i: Top-inx repeatTable[inx+i]->Table [i nx+ i-1 ]

for);Top-1->Top;leave Search

if)for)#);#)

Figure 5.2 PatternRegister .

– it is a commonprogrammingerror to confusethesetwo issues.In object-orientedprogrammingthis distinctionis thedifferencebetweenthereference

Page 72: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.6 ASSIGNMENTAND EQUALITY 61

to an objectandthe stateof an object. In somelanguagesthis differenceisnot madeexplicit in the syntax, implying that the programmermay not beawareof whethera referenceor the stateof an object is beingmanipulated.In theBETA syntaxthereis anexplicit distinctionbetweenmanipulationof areferenceandmanipulationof the stateof anobject. Considerthe followingobject:

(# R1,R2: @Point;R3,R4: ˆPoint

do &Point[]->R3[]; &Point[]->R4[];(1,1)->(R1.x,R1.y); (2,2)->(R2.x,R2.y);(3,3)->(R3.x,R3.y); (4,4)->(R4.x,R4.y);L1:R3[]->R4[]; R1[]->R3[];L2:(100,200)->&R1.MoveL3:

#)

Figure5.3 shows the stateof the objectat the pointsL1, L2 andL3, respec-tively.

R1 andR2 denotepartobjects,whereasR3 andR4 denoteseparateobjects.At L2 it canbeseenthatexecutionof the referenceassignmentsimplies thatR1 andR3 denotethe sameobject. At L3 it canbe seenthat the imperative(100,200)->&R1.Move alsoaffectstheobjectdenotedby R3.

Next weconsiderassignmentof integerobjects:

(# a,b,c: @integerdo 111->a; 222->b; 333->c;

L1:a->b;L2:c->b;L3:

#)

Figure5.4 shows the stateof theabove objectat L1, L2 andL3 respectively.Notethata, b andc arenot referencesto values,but areobjectshaving astatecorrespondingto thevalues111 , 222 and333 . At L2 it canbeseenthata andb have the samevalue(state);at L3 it canbe seenthat a is not affectedby anew assignmentto b.

Thisexampleshows thatintegerobjectsandtheassignmentof integerob-jectsbehave like ordinaryvariablesandassignmentin traditionalprocedural

Page 73: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

62 IMPERATIVES

R2

at L1

R3

R4

R1 x

y

x

y

2

2

at L3

R3

R4

R2

R1 x

y

x

y

y

x

y

x 4

4

3

3

y

x

y

x

3

3

4

4

2

2

101

201

1

1

at L2

R3

R4

R2

R1 x

y

x

y

y

x

y

x

3

3

4

4

1

1

2

2

Figure 5.3 Illustrationof referenceassignment.

programminglanguages,i.e.assigningobjecta to objectb consistsof copyingthestateof a to b. This form of assignmentis calledvalueassignment.

Page 74: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.6 ASSIGNMENTAND EQUALITY 63

at L1 at L2

a

b

111

222

333c

at L3

a

b

c

a

b

c

111

333

333

111

111

333

Figure5.4 Basicvalueassignment.

It is alsopossibleto definevalueassignmentfor patternslike Point . ThePoint patternmayberedefinedsuchthatvalueassignmentof Point objectsis possible,asin thefollowing object:

{Note:the current definition of the Point pattern must}{be revised in order for this example to be legal!}{For purposes of discussion only.}(# R1,R2: @Point;

R3,R4: ˆPointdo &Point[]-> R3[]; &Point[]->R4;

(1,1)->R1; (2,2)->R2; (3,3)->R3; (4,4)->R4;L1:R1->R3; R2->R4;L2:R3->R2; (5,5)->R1L3:

#)

Themeaningof theabove assignmentsmaybe interpretedasfollows: anas-signmentlike:

(1,1)->R1

assignsthevalue1 to x andy . An assignmentof theform:

R1->R3

assignsthex andy attributesof R1 to thex andy attributesof R3. Figure5.5shows thestateof theabove objectat L1, L2 andL3, respectively. Thediffer-encefrom Figure5.3maybeobserved.

Valueassignmentfor non-basicobjectscouldbedefinedasapurecopy ofthestateof theobject. This would besufficient for theabove example.Mostlanguagesdefinevalueassignmentasa purecopy. The stateof an object is,

Page 75: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

64 IMPERATIVES

R2

at L1

R3

R4

R1 x

y

x

y

2

2

at L3

R3

R4

R2

R1 x

y

x

y

y

x

y

x 4

4

3

3

y

x

y

x

1

1

2

2

1

1

5

5

1

1

at L2

R3

R4

R2

R1 x

y

x

y

y

x

y

x

1

1

2

2

1

1

2

2

Figure5.5 Illustrationof valueassignment.

however, a representationof anabstractvaluecapturingthe interestingprop-ertiesof theobject’sstate.It is oftenthecasethattwo or moredifferentstatesrepresentthesameabstractvalue.For this reason,theprogrammershouldbe

Page 76: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.6 ASSIGNMENTAND EQUALITY 65

ableto definethemeaningof assignmentandequality.The first exampleshows how assignmentmay be definedfor the Point

pattern:

Point:(# x,y: @integerenter(x,y)exit(x,y)#)

Assignment(andaswe shall seelater, equalityalso)is definedby meansoftheenterandexit parts.Considerthefollowing assignments:

(11,22)->R1; {1}R1->R2; {2}

In line 1, thevalues11 and22 areassignedto theenterpartof R1, i.e. x andy areassigned.In line 2, the elementsof the exit-list of R1 areassignedtothe correspondingelementsof the enter-list of R2. As canbe seen,thereistechnicallynodifferencebetweenassignmentandparametertransferin apro-cedureinvocation.ThePoint patternmayhavea do-part,asin thefollowingexample:

Point:(# x,y,count: @integerenter(x,y)do count+1->countexit(x,y)#)

As for procedureinvocation,thedo-partwill be executedeachtime a Pointobjectis assignedfrom and/orto. Thenumberof timesthis happensfor eachobject is countedin the Count variable. By makingCount global to Point ,thetotal numberof accessesto Point objectscouldbecounted.

5.6.1 Equality

As thereis a distinctionbetweenreferenceassignmentandvalueassignment,thereis alsoadistinctionbetweenreferenceequalityandvalueequality. Con-siderthefollowing example:

(# a,b: @integer;R1, R2: ˆPoint;B1,B2,B3: @boolean

Page 77: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

66 IMPERATIVES

do ...(a = b)->B1; {1}(R1[] = R2[])->B2; {2}(R1 = R2)->B3 {3}

#)

In line 1, a valuecomparisonbetweentwo integerobjectsis described.Valueequalityfor the basicpattern,like integer , works in the usualway. Line 2describesareferencecomparison:thecomparisonis trueif thetwo referencesdenotethesameobject.

Line 3 describesavaluecomparisonbetweentwo point objects:this com-parisonis true if the ‘value’ of the two objectsis the same. Valueequalityheremeansthatelementsof theexit list of R1 arecomparedto correspondingelementsof theexit list of R2, i.e. theexit partis alsousedfor describingwhatto comparein avalueequality.

If a do-partis presentit will be executedprior to comparisonof the exitlists. TheCount variablein Point will alsocountthenumberof comparisons.

It shouldnow bepossibleto understandthedetailsof all theexamplesofif-imperativesfrom Section5.3 involving valueequality.

Furtherdetailsof assignmentandequalityaredescribedin Section5.8.

5.6.2 Basicpatterns

Referenceassignmentand equality are not available for basicpatternslikeinteger . In principle, thereis no reasonfor this restriction; the restrictionis only dictatedby efficiency reasons.If it waspossibleto have generalref-erencesto, say, integer objects,then memorymanagementwould be moreexpensive. However, in practicetheredoesnotseemto beany needfor this.

5.7 Computed referencesand computed remotename

Considerthebankingexamplein Figure4.2with thefollowing procedurepat-ternadded.It findstheaccountof a givencustomer, andif thecustomerdoesnot haveanaccount,anew oneis created.

GetAccount:(# C: ˆCustomer; rA: ˆAccountenter C[]do (for i: noOfCustomers repeat

(if C.name[]->CustomerFile[i].name.equa l//true then AccountFile[i][]->rA[]

if)

Page 78: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.8 DETAILED DESCRIPTIONOF EVALUATIONS 67

for);(if rA[]//NONE then C[]->NewAccount->rA[] if)

exit rA[]#)

Thispatternmaybeusedas:

Joe: ˆCustomer; acc: ˆAccount; bal: @integer...Joe[]->BankSystem.getAccount->acc[ ];acc.balance->bal

If we are simply interestedin the balanceof Joe ’s account,we may useacomputedreferenceto accessthebalance andavoid introducingthereferencevariableacc :

(Joe[]->BankSystem.getAccount).bal ance- >bal

Theresultof theevaluationJoe[]->BankSystem.getAccount is a dynamicreferenceto an Account . The evaluationis saidto be a computedreference,sinceit is theresultof anevaluationof aproceurepattern.A procedurepatterncomputesa referenceif its exit-list hasoneelementwhich mustbea dynamicreference.A computedreferencemay be usedin a computedremotename,which hastheform:

(ComputedReference).name

The result of ComputedReference must be a referenceR. Let R be quali-fied by T. The name must be an attribute of T. The computedremotename(ComputedRemote).name denotestheattributename of theobjectreferencedby R.

Since Joe[]->BankSystem.getAccount computesa referenceto theAccount objectof Joe , thecomputedremotename:

(Joe[]->BankSystem.getAccount).bal ance

denotesthebalance accountof Joe ’saccount.

5.8 Detaileddescription of evaluations

In Chapter2,differentkindsof propertiesthatmaybeusedto characterizephe-nomenawerebriefly mentioned.Amongtheseweremeasurablepropertiesofphenomena.A measurablepropertymaybeobtainedby observingthestateofoneor moreobjects.To performsuchanobservationit is necessaryto perform

Page 79: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

68 IMPERATIVES

a measurement, which is an action-sequencethat resultsin a measurement.1

A measurementmaybedescribedby a valueand/orcomparedto othermea-surements.A valueis an abstractionwhich classifiesmeasurements.In thefollowing weshallsaythata measurementproducesavalue.

In BETA a measurableproperty is reflectedby an object that producesa valueasa resultof executingthe object. The representationof a valueisdescribedby the exit-part of the objectbeingexecuted.Sincemeasuringin-volvesacomputation,theresultingvaluemaydependuponthestateof severalobjects.

Thenotionof assignmentis dualto measurement.Assignmentmeansen-forcing avalueuponthestateof oneor moreobjects.

An evaluationis the basicmechanismfor specifyingan actionsequencethatmaycausestatechangesand/orproduceavalue.Thenotionof anevalua-tion is aunifiedapproachto assignment,function-callandprocedure-call.Anevaluationmayspecifyeitheranimperative,ameasurement,anassignmentora transformation:

� An evaluation-imperative(or justevaluation) describesanactionsequence.� An evaluationspecifyinga measurementdescribesanactionsequencethat

computesavalue.� An evaluationspecifyingan assignmentdescribesan actionsequencethat

enforcesavalueon thestateof someobjects.� An evaluationspecifyinga transformationdescribesanactionsequencethat

enforcesa value on the stateof someobjectsand computesa value. Atransformationis thusacombinationof anassignmentandameasurement.

Considerthefollowing object:

X: @(#enter E0do E1->E2->E3exit E4#)

ThewholeevaluationE1->E2->E3 describesanevaluationimperative,E4 andE1 describemeasurements,E2 describesa transformation,andE3 andE0 de-scribeassignments.Thiswill befurtherelaboratedbelow.

An evaluationmaybedescribedasanobject,anevaluationlist, or asanas-signmentevaluation.In thefollowing, themeaningsof thesethreeevaluationformsaredescribed.

1Note that measurementhere is both usedas an action and as the result of an action.Accordingto Webster:1. The actof measuringor conditionof beingmeasured.2. Extent,size,etc.asdeterminedby this.

Page 80: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.8 DETAILED DESCRIPTIONOF EVALUATIONS 69

5.8.1 Object evaluation

An evaluationmay be describedasan objectevaluation. The objectmay beobtainedby meansof a referenceor agenerationusingapattern.It mayspec-ify anevaluationin oneof thefollowing ways:

� Imperati veTheresultof executingthedo-partof theobject.� MeasurementTheresultof executingthedo-partof theobjectfollowedby

evaluatingthe exit-part of the object. The valueproducedis the measure-mentproducedby theexit-part.

� AssignmentTheobjectmaybeassigneda value. Thevalueis assignedtotheenterpartof theobjectfollowedby executingthedo-partof theobject.

� Transformation A valueis enforcedupontheassignmentdescribedin theenter-part of the object, followed by executingthe do-partof the object,followed by evaluatingthe measurementdescribedin the exit-part of theobject.

In thefollowing, exampleX is theobjectdefinedabove:

� Imperati veAn objectevaluationusedasanimperativemaybespecifiedasfollows:

X

Theresultof this is thatE1->E2->E3 is executed.� MeasurementAn objectevaluationusedasa measurementmaybespeci-

fiedasfollows:

X->...

Theresultof this is thatE1->E2->E3 is executedfollowedby theexecutionof E4. Thevalueproducedby E4 will beassignedto whateverthedots(... )standfor.

� AssignmentAn objectevaluationusedasanassignmentmaybespecifiedasfollows:

...->X

Theresultof this is that thevalueproducedby whatever thedotsstandforis assignedto E0, whereafterE1->E2->E3 is executed.

� Transformation An object evaluation usedas a transformationmay bespecifiedasfollows:

Page 81: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

70 IMPERATIVES

...->X->...

Theresultof this is thatthevalueproducedby theleft-mostdotsis assignedto E0, then E1->E2->E3 is executed,and finally E4 is executed,and thevalueproducedis assignedto theright-mostdots.

5.8.2 Evaluation list

An evaluationlist hastheform:

(E1,E2,...,En)

An evaluationlist mayspecifyanevaluationin oneof thefollowing ways:

� Imperati veThen imperativesEn areevaluatedin someorder.� MeasurementDescribesa compoundvalue(M1,M2,...,Mn) , whereeach

Mi is describedby Ei .� AssignmentDescribesassignmentof acompoundvalue(M1,M2,...,Mn) ,

whereeachMi is assignedto Ei .� Transformation Describes a transformation of a compound value

(M1,M2,...,Mn) into anothercompoundvalue (Q1,Q2,...,Qn) , whereeachtransformationEi describesthetransformationfrom Mi to Qi .

Considerthefollowing example:

(# x,y,z: @integer;A,B: @

(# i,j,k: @integerenter(i,j,k)do i+2->i; j+3->j; k+4->kexit(k,j,i)#)

do 111->x; 222->y; 333->z;(x,y,z); {1}(x,y,z)->A; {2: A.i=113, A.j=225, A.k=337}A->(x,y,z); {3: A.k=x=341, A.j=y=228, A.i=z=115}A->(x,y,z)->B; {4: A.k=345=x, B.i=347,

A.j=231=y, B.j=234,A.i=117=z, B.k=121}

#)

� Imperati ve � 1 � above is anexampleof anevaluationlist usedasanimper-ative. This exampleis not interesting,sinceexecutionof x , y andz hasnoeffect.

Page 82: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.8 DETAILED DESCRIPTIONOF EVALUATIONS 71

� Measurement � 2 � is an exampleof an evaluationlist usedasa measure-ment:theevaluation(x,y,z) describesameasurementproducingthecom-poundvalue(111,222,333) , which is assignedto A.

� Assignment � 3 � is an exampleof an evaluation list usedas an assign-ment: the compoundvalue producedby A ((341,228,115) ) is assignedto (x,y,z) .

� Transformation � 4 � is an exampleof an evaluationlist usedasa trans-formation: the compoundvalue (345,231,117) is assignedto (x,y,z) ,which is subsequentlyassignedto B.

5.8.3 Assignmentevaluation

An assignmentevaluationhastheform:

E1->E2->...->En

It mayspecifyanevaluationin oneof thefollowing ways:

� Imperati ve

– E1 describesameasurementproducingthevalueM1

– E2 describesa transformationbeingassignedthevalueM1andproducingthevalueM2

– ...

– En describesanassignmentbeingassignedthevalueMn-1

� Measurement Identicalto imperative, exceptthat En describesa transfor-mationwhich, in additionto beingassignedMn-1 , alsoproducesMn.

� AssignmentIdenticalto imperative,exceptthatE1 describesa transforma-tion which is assignedsomemeasurementM0andproducesM1.

� Transformation Identicalto imperative,exceptthatE1 describesatransfor-mationwhich is assignedsomevalueM0andEn describesa transformationproducingsomevalueMn

Considerthefollowing example:

(# a,b,c,d,e,f,g: @integerenter a->b {1}do b->c->d->e {2}exit f->g {3}#)

� Imperati ve � 2 � is anexampleof anassignmentevaluationusedasan im-perative.

Page 83: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

72 IMPERATIVES

� Measurement � 3 � is an exampleof an assignmentevaluationusedas ameasurement.

� Assignment � 1 � is anexampleof anassignmentevaluationusedasanas-signment.

� Transformation c->d within � 2 � is an exampleof an assignmentevalua-tion usedasa transformation.

Notethat therecursive definitionof assignmentmeansthat thedo-partof ob-jectsbeingassignedduringavalue-transferarealsoexecuted.

5.8.4 Value relations

Values(measurements)canbecomparedusingtherelationaloperators=, <>,etc. In addition,theif-imperativemakesuseof valueequality.

Let E1 andE2 betwo evaluationsspecifyingmeasurements.E1 andE2 areequalif the two measurementsM1andM2 producedby evaluatingE1 andE2,respectively, areidentical.

For the basicpatternsinteger , char , boolean and real we have thatinteger -objectsareassignableto integer -objects,etc.As describedin Sec-tion 3.3.3,it is alsopossibleto assignchar objectsto integer objects,etc.

It is also possibleto assigninteger objectsto real objects,and viceversa:

I: @integer; X: @real...I->X; X->I; 13->X; 3.14->I

Suchassignmentsimply the usualconversionbetweeninteger numbersandfloatingpointnumbers.

As alsomentionedin Section3.3.3,it is alsopossibleto compareinstancesof thebasicpatternsusingrelationaloperators.

As mentionedin Section4.2, it is possibleto assigna text constantandatext objectto anothertext object.It is, however, notpossibleto comparetextobjectsusingtherelationaloperators.Thetext patterndefinedin theMjølnerBETA Systemhasvariousattributesfor comparingtext objects,includinganoperationthattestsfor theequalityof two text objects:

T1[]->T2.equal

5.9 Block structur eand scoperules

The differencebetweenthe declaration of a nameand the applicationof anameis a fundamentalissue.Considerthefollowing object:

Page 84: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.9 BLOCK STRUCTUREAND SCOPERULES 73

(# R1: @Point; {1}R2: ˆPoint {2}

do R1[]->R2[] {3}#)

Line 1 containsa declarationof thenameR1 andanapplicationof thenamePoint . Theapplicationof Point refersto a declarationof Point somewhereelsein theprogram.Line2hasadeclarationof R2andanapplicationof Point .Thenamesusedin line 3 arebothapplicationsreferringto thedeclarationsinlines1 and2.

Most programminglanguageshave a unit in which all declarationsofnamesmustbe different,i.e. the samenamemay not be declaredmorethanonce. In addition,eachdeclarednamehasa scope, which is that part of theprogramtext whereapplicationsof thesamenamereferto thedeclaration.

In BETA, all namesdeclaredin the attribute part of an objectdescriptormust be unique. The scopeof a declarednameis the object descriptorinwhich it is declared.Sinceobjectdescriptorsmaybetextually nested,adecla-ration in aninternalobjectdescriptormayhidea declarationin theenclosingobjectdescriptor. Also, theindex variableof a for-imperativeandthelabelofa labeledimperative mayhidenamesdeclaredin theenclosingprogramtext.In thefollowing example,anidentifierof theform a 1 refersto thea declaredin line 1, etc.:

(# a: ...; b:...; i:...; {1}P: (# a:...; c: ... {2}

do (for i: ... repeat {3}{Visible names:

b_1,a_2,c_2,i_3}for)

#)do (# b: ... {8}

{visible names a_1,i_1,b_8}#)

#)

Theabove scoperulesarethe traditionalblock structurerulesfrom Algol 60andPascal,but they do not cover remoteidentifierslike R1.Move . Considerthedeclaration:

R: @T

Any attribute,saya, declaredin T maybeaccessedusinga remoteidentifierof theform:

R.a

Page 85: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

74 IMPERATIVES

In BETA, objectdescriptorsmaybetextuallynested.Theexamplessofarhaveshown up to threelevelsof textually nestedobjectdescriptors:theprogram,a pattern(like Point ) andoperations(like Move). In fact, objectdescriptorsmaybetextually nestedto anarbitrarydepth:this is known asblock structure.

Block structureis animportantmechanismfor structuringindividualcom-ponentsof a largeprogram,andis a meansfor providing locality of declara-tions.For moreexamplesof usingblockstructure,seeChapter8.

We have previously mentionedtheorigin attributeusedto accessglobalattributes.In fact,all objectshaveanorigin attributereferringto its enclosingblock. Considerthefollowing example:

(# a: @integer;P: (# b: @integer;

T: (# c: @integerdo a+b->c;#)

do a * 2->b#);

do 1->a; &P#)

Theuseof globalattributesis handledby usingorigin asfollows:

(# a: @integer;P: (# b: @integer;

T: (# c: @integerdo origin.origin.a+origin.b->c;#)

do origin.a * 2->b#);

do 1->a; &P#)

The above scoperules will later be extendedto cover sub-patternsandvirtual patterns,asintroducedin Chapters6, 7 and9.

5.10 Object kinds and construction modes

Thissectionintroducesthenotionsof objectkindandconstructionmode. Ob-ject kind is usedto classify objectsas either sequentialor multi-sequential(coroutinesor concurrency). Constructionmodedefinesthedifferentwaysforconstructingandgeneratingobjects.

Page 86: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.10 OBJECTKINDS AND CONSTRUCTION MODES 75

5.10.1 Object kinds

In this chapterit hasbeenshown how to generateobjectscorrespondingtoclassobjects,andprocedureobjects,etc. Theseobjectsall relateto programexecutionsconsistingof onesequentialactionsequence.It ispossibletogener-ateobjectswhich maybeexecutedascoroutinesandasconcurrentprocesses.For this purposethereis a distinctionbetweendifferentobjectkinds. BETAhastwo kindsof objects:componentanditem. Thekind of anobjectspecifieshow theobjectcanbeexecuted.

� A componentobject(coroutine)maybeexecutedconcurrentlyoralternatelywith othercomponents.

� An item object is a partial action sequencecontainedin a componentoritem.

In this chapterobjectsof the item kind have beendescribed.Objectsof thecomponentkind aredescribedin Chapters13–15.

5.10.2 Construction modesand inserted objects

In theprecedingsectionstwo differentmodesfor generatingobjectshavebeenshown. Objectsmaybe createdstaticallyby declaration,or createddynami-callybya‘new’-imperative.Thesedifferentwaysof creatingobjectsarecalledconstructionmodes. Theconstructionmodegivesriseto two sortsof objects,respectively calledstatic anddynamicobjects. Thereis a third constructionmodecalledinsertedobject, describedin thenext section.

As mentionedpreviously, the invocationof a patternasa proceduregivesrise to thegenerationof anobjectfor representingtheaction-sequencebeinggeneratedbyexecutionof theprocedure.Thisleadsto thegenerationof alargenumberof small objects. Theseobjectshave to be generatedand removedby the storagemanagementsystem,which may be quite expensive. For thisreasonit is possibleto describethatsuchprocedureobjectsbegeneratedasapermanentpartof theobjectinvoking theprocedurepattern.

As shown previously, a patternP may be usedto generatea procedureobjectasfollows:

E->&P->A

Thegenerationof aninserteditem is doneasfollows:

E->P->A

TheP object(calledan inserteditem) will beanintegral partof theenclosingobject. This inserteditem will then be executedwhen control reachesthe

Page 87: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

76 IMPERATIVES

evaluationimperative. Thestateof this P item will beundefinedprior to eachexecutionof it. Thenotionof aninserteditemis similarto anin-line procedurecall.

Apart from the allocation, the executionof an inserteditem is like theexecutionof any other object. In the above case,the executionassignstheoutputof E to theenter-partof the insertedP item, andcausesthe instancetobeexecuted.Finally, theexit-partof theinsertedP instanceis assignedto A.

Theevaluation:

(11,22)->P1.Move

specifiesan inserteditem for the patternP1.Move. This temporaryinstanceis actually allocatedas part of the object executingP1.Move . In this way,P1.Move describesan in-line allocationof a Move instance.

As alreadymentioned,insertedobjectsareallocatedin-line in thecallingobject. Themotivationfor insertedobjectsis a matterof efficiency, sincethecompilermaycomputethestoragerequirementsof thecallingobject.Insertedobjectsareanalogousto staticobjectsin the sensethat they areallocatedaspartof theenclosingobject.

With this semanticsof inserteditems,it follows thatinserteditemscannotbeusedto describerecursive procedures,sincethis will leadto aninfinite re-cursion.This is analogousto staticitems,whichcannotbeusedfor describingrecursivedatastructures.

5.10.3 Summary of construction modes

As mentionedin theprevioussection,objectsmaybeof two differentkinds.Theobjectsdescribedin thischapterareof theitemkind; below wesummarizetheconstructionmodesfor objectsof thiskind:

� Static items The following declarationsdescribethe generationof staticitems:

E: @P; {1}F: @P(# ... #); {2}G: [...] @P; {3}H: [...] @(# ... #) {4}

whereP is a patternname,E andF arestatic references,andG andH areindexedcollectionsof staticreferences.Thestaticitemsgeneratedby lines1 and3 arepatterndefined,whereasthe static itemsgeneratedby lines 2and4 aresingular.

� Dynamic items The following imperativesdescribethe generationof dy-namicitems:

Page 88: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.10 OBJECTKINDS AND CONSTRUCTION MODES 77

(# P: (# I,J: @integer;enter(I,J)do I+J->Iexit(J,I)#);

E: @P; {declaration of a static (part) item}X: ˆP; {declaration of reference to an item}N,M: @integer;

do {generation of a dynamic P-item and}{subsequent assignment of the reference X}&P[]->X[];

{an evaluation using static, inserted and dynamic items}(3,4)->E->P->E->&P- >X- >P- >(N ,M)

#)

Figure5.6 Exampleof dynamicitems.

e1->&P->e2; {1}e3->&P(# ... #)->e4; {2}&P[]->R1[]; {3}&(# ... #)[]->R2[] {4}

Lines1 and2 describethegenerationof dynamicitemswhich areimmedi-atelyexecutedasprocedureobjects.Lines3 and4 describethegenerationof dynamicitems,wherereferencesto thenew objectsareassignedto dy-namicreferenceattributes.Lines1 and3 describethegenerationof patterndefinedobjects,whereaslines 2 and4 describethe generationof singularobjects.

� Inserted items The following imperativesdescribethe generationof in-serteditems:

e1->P->e2; {1}e3->(# ... #)->e4; {2}

Line 1 describesthegenerationof a patterndefinedobject,whereasline 2describesthegenerationof asingularobject.

In Figure5.6, examplesaregiven of the threedifferentconstructionmodes.The lastevaluationinvolvestwo executionsof thestaticitem E, executionoftwo different inserteditems(specifiedby the two Ps), andexecutionof two

Page 89: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

78 IMPERATIVES

differentdynamicitems,onedenotedby X andananonymousonegeneratedduringtheevaluationby &P.

Thenotionsof kind andconstructionmodeareorthogonal,sinceobjectsofthekind componentmayalsobecreatedeitherstatically, insertedor dynami-cally.

5.11 Exercises

(1) Write apatternthattransformsaUNIX pathof theform:

/users/smith/src/beta

into thecorrespondingMacintoshform:

:users:smith:src:beta

andviceversa.

(2) Modify the bankingexamplefrom Exercise2 in Chapter3. Include apatternfor computingthesumof thebalanceof all accountsfor aspecificcustomer, andonefor deletingall accountsfor aspecificcustomer.

(3) Write a patternthat computesall prime numberslessthan100usingthesieve of Eratosthenes.Constructa list of objectscontainingthenumbers2 "!"!#!# 100. For eachi where2 <= i <= 100 , eliminateall elementsofthelist containinga numberthat is divisible by i . Theremaininglist willhaveall primenumberslessthan100.

Write thepatternin suchawaythatit is easyto useavalueotherthan100,i.e. thevalue100shouldbeaparameterto thepattern.

Make a solutionwherethe list is representedusinga repetition,andonewhereit is a linked list using references.The prime patternshouldbeindependentof theactualrepresentationof thelist.

(4) Write patternsfor standarddatastructureslike stack,queue,dequeandtree.

(5) Designandimplementasimplesodamachinewhich‘dispenses’twokindsof drinks, cola and juice. The sodamachineshouldhave the followingproperties:

1. Oneor morecoinsmaybeinserted.

2. If enoughmoney has been inserted, the appropriatedrink pluschangemaybeobtained.

3. Themachineshouldkeeptrackof thecurrenttotalamountof money,andthecurrentnumberof colasandjuices.

Page 90: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

5.12 NOTES 79

4. Thecustomermayresetthemachineandgetbackthemoney he/shehasinserted.

5. It will bepossibleto refill themachineandtakeout themoney.

6. It will bepossibleto adjusttheprice for thedrinks. Theprice for acolaanda juicemaybedifferent.

5.12 Notes

Imperativessuchasassignment,for-imperative, if-imperative andlabelsandjump-imperativeshave beenaroundsincethe early programminglanguages.In mostlanguages,theBETA assigment:

exp->V

is expressedlike

V := exp

For BETA it wasfelt that it is morenaturalto expressan assignmentin theorderof evaluation. This is especiallythecasefor multiple assignmentsandcombinationsof function calls. In BETA it is possibleto combinearbitraryfunctioncalls in anevaluation.Considerthefollowing Algol-lik e assignmentstatement,whereF, GandH arefunctions:

var := F(G(exp1),H(exp2,exp3))

Thismaybeexpressedin BETA in thefollowing way:

(exp1->G,(exp2,exp3)->H)->F->var

In somelanguagesthereis a distinctionbetweena procedureanda function,in thesensethata functionmayreturna valueandbeusedin anexpression.In most languages,a function may returnexactly onevalueandnot a list ofvalues,asin BETA. TheBETA patternis, amongotherthings,aunificationofproceduresandfunctions,anda procedure/functionpatternmay returna listof values. As mentionedin Section3.3.2,the importantdistinctionbetweena procedurepatternanda function patternis that the latter shouldnot haveside-effects.

Wehavementionedthesimilaritiesbetweeninserteditemsandin-line pro-cedurecalls,andbetweendynamicitemsandAlgol-lik e procedureactivationrecords.We alsonotethatastaticitemmaybeusedasastaticsubroutine.

The registerexamplein Figure5.2 is similar to Hoare’s small integerset(Hoare,1972).

Page 91: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

80 IMPERATIVES

Page 92: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 6

Sub-patterns

As describedin Chapter3, patternsmay be usedto representconcepts.Theforms of patternsusedso far are sufficient as long as the extensionsof theconceptsbeing modeledare disjoint, i.e. the set of objectsgeneratedfromdifferentpatternsaredisjoint. In practice,therearenumeroussituationswherethis is notthecase.Considertheclassificationhierarchyfor animalsillustratedin Figure2.2in Chapter2. Theextensionsfor lion andtigerareclearlydisjoint,but the extensionfor predatorincludesthe extensionsfor lion and tiger. Inthischapter, languageconstructsfor representingclassificationhierarchiesliketheseareintroduced.

6.1 Specializationby simple inheritance

Considera travel agency which handlesreservationsof severalkinds,includ-ing flight andtrain reservations.Whendesigninga computersystemfor han-dling reservations,it is thusnaturalto formulateconceptssuchastrain reser-vation andflight reservation. Patternsfor representingthe conceptsof flightreservationandtrain reservationmaybedescribedin thefollowing way:

FlightReservation:(# Date: ...

Customer: ...ReservedFlight: ...ReservedSeat: ...

#);TrainReservation:

(# Date: ...Customer: ...ReservedTrain: ...ReservedCarriage: ...ReservedSeat: ...

81

Page 93: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

82 SUB-PATTERNS

Reservation

FlightReservation TrainReservation

Figure6.1 Classificationhierarchyfor reservations

#)

The above patternsinclude the propertieswe may want to model for flightreservationsandtrain reservations.

Flightandtrainreservationshavesomecommonpropertiessuchasthedateof thereservationandthecustomerwho hasmadethereservation. They alsodiffer in variousways:aflight reservationincludesareferenceto theflight andinformationaboutreservedseat,etc.;a train reservation includesinformationaboutthe train, thecarriageandtheseat.In additionto theflight reservationandtrain reservationconcepts,it is usefulto defineageneralconceptof reser-vation covering the commonpropertiesof flight andtrain reservations. Thisgivesriseto a simpleclassificationhierarchyfor reservations,asillustratedinFigure6.1.

Supposethat we also want to model the conceptreservation, which in-cludesthe commonpropertiesof flight reservationsand train reservations.Thiscouldbedescribedas:

Reservation:(# Date: ...

Customer: ...#)

There are, however, no relations betweenthe pattern Reservation andthe patternsFlightReservation and TrainReservation . The descrip-tion does not include the property that Reservation is a generalizationof FlightReservation and TrainReservation . The objectscreatedasinstancesof the three patternswill form three disjoint sets (have disjointextensions). Instancesof Reservation bear no relation to instancesofFlightReservation . Finally, the descriptionof commonattributessuchasDate andCustomer hasbeenrepeatedthreetimes.

In the real world we considerall flight reservations to be reservations.Likewise,in our programexecutionwe alsowant to considerall instancesof

Page 94: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.1 SPECIALIZATION BY SIMPLEINHERITANCE 83

FlightReservation to beinstancesof Reservation . Similarly, all instancesof TrainReservation shouldalsobeconsideredinstancesof Reservation .

For the purposeof representingsuchclassificationhierarchies,patternsmaybeorganizedin sub-patternhierarchies.A sub-patternis a patternwhichis aspecializationof anotherpattern.

Thereservationconceptsmaybemodeledin thefollowing wayusingsub-patterns:

Reservation:(# Date: @DateType;

Customer: ˆCustomerRecord#);

FlightReservation: Reservation(# ReservedFlight: ˆFlight;

ReservedSeat: ˆSeat;#);

TrainReservation: Reservation(# ReservedTrain: ˆTrain;

ReservedCarriage: ˆCarriage;ReservedSeat: ˆSeat;

#)

By prefixingtheobjectdescriptorfor FlightReservation by Reservation ,the object descriptor for FlightReservation inherits all the declara-tions from Reservation , meaningthat the attributes Date and Customerwill be inherited from Reservation . Objects generatedaccording toFlightReservation will have the attributes Date and Customer (fromReservation ), plusReservedFlight andReservedSeat .

Similarly, objectsgeneratedaccordingto TrainReservation will havethe attributes Date , Customer (from Reservation ), ReservedTrain ,ReservedCarriage andReservedSeat .

This is an example of specialization by simple inheritance of at-tributes.We saythatFlightReservation andTrainReservation aresub-patterns of Reservation , and that Reservation is the super-pattern ofFlightReservation andTrainReservation .

Thereasonthata patternlike FlightReservation is calleda sub-patternof Reservation is that the setof all FlightReservation objectsis a sub-setof all Reservation objects.Similarly, thesetof all TrainReservationobjects is a subsetof all Reservation objects. In addition, the set ofFlightReservation objectsandthe setof TrainReservation objectsaredisjoint, illustratedin Figure6.2. Thesamemaybeexpressedin termsof ex-tensionsof concepts:theextensionof FlightReservation is a subsetof theextensionof Reservation .

Page 95: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

84 SUB-PATTERNS

Reservation

FlightReservation TrainReservation

Figure6.2 Subsetrelationsfor extensionsof reservationpatterns

Thesetof objectsgeneratedfrom a patternconstitutesits extension.Theintension of a conceptrepresentedby a pattern is defined by its object-descriptor, which representsthe propertiesof the object in termsof its at-tributes and action-part. For example, the Reservation pattern’s object-descriptorstatesthat elementsin the extension(Reservation objects)allhave a Date and a Customer attribute. For the FlightReservation pat-tern,additionalpropertiesaredescribed:elementsin theextensionalsohavea ReservedFlight anda Customer attribute. Whenwe definea sub-pattern,we definea patternthathassomeadditionalpropertiesin additionto thoseofthesuper-pattern.Addingnew propertiesrestrictsthesetof possibleinstances.Thismaybesummarizedasfollows:

� The intensionof a sub-patternextendsthe intensionof the super-pattern,sincemorepropertiesareadded.

� The extensionof a sub-patternis a subsetof the extensionof the super-pattern,sincemorepropertiesmustbefulfilled.

As alreadymentioned,thekind of propertiesthatcanbeaddedarethosethatcanbedescribedby anobject-descriptor. Examplesof suchpropertiesincludenew attributes,the qualificationof the attributes,whetheror not it is a partobjector a referenceto a separateobject,etc. Propertiesdescribingactionsexecutedby an objectareanotherexample. Later in this chapterwe presentexamplesof specializingtheaction-part.

Object generation

Thereservationpatternsmaybeusedto generateobjects:

Page 96: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.1 SPECIALIZATION BY SIMPLEINHERITANCE 85

T1: @TrainReservation;F1: @FlightReservation;T2: ˆTrainReservation;F2: ˆFlightReservation;...T1[]->T2[]; &FlightReservation[]-> F2[]

It is alsopossibleto generateinstancesof Reservation :

R1: @Reservation;R2: ˆReservation...&Reservation[]->R2[];

This may not be very usefulsinceour reservation systemwill handleeithertrain reservationsor flight reservations. Patternslike Reservation that arejust usedassuper-patterns,but neverusedfor generatinginstances,arecalledabstractsuper-patterns.

In Section3.2.5thenotionof aqualifiedreferencewasintroduced.Theref-erencesR1,T1,F1 ... arequalifiedby Reservation , TrainReservation ,FlightReservation , ... . Thequalificationof a referencerestrictsthesetofobjectsthatmaybereferredto by thereference.In addition,thequalificationdetermineswhich attributesmaybedenotedby remoteaccess.For R1, T1,F1 ... it is possibleto accessattributeslike:

R1.Date T1.Date T1.ReservedTrain F2.ReservedFlight ...

whereasthefollowing remoteidentifiersarenot legal:

R1.ReservedSeat T2.ReservedFlight F1.ReservedTrain ...

Using super-patterns for qualifying references

Considerthefollowing declarations:

R: ˆReservation;F: ˆFlightReservation;T: ˆTrainReservation

Thesedeclarationsstatethat R mayrefer to Reservation objects,F mayre-fer to FlightReservation objects,andT may refer to TrainReservationobjects. From a conceptualpoint of view, FlightReservation objectsarealsoReservation objects,which meansthat R shouldbeallowedto refer toFlightReservation objects,andthatis alsotherule. It is possibleto performthefollowing referenceassignment:

Page 97: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

86 SUB-PATTERNS

Date

FlightReservation

Customer

ReservedFlight

ReservedSeat

R

F

T

At L1

R

F

T

Date

FlightReservation

Customer

ReservedFlight

ReservedSeat

At L2

Figure6.3 A Reservation referencemayreferto instancesof sub-patternsof Reservation .

L1:F[]->R[];

L2:

At thelabelL1 it isassumedthatF denotesaninstanceof FlightReservation ;at thelabelL2, R will alsoreferto this instanceof FlightReservation , illus-tratedin Figure6.3.

Using R it is possible to refer to the attributes Date and Customeras describedby the Reservation pattern. This meansthat R.Date andR.Customer are legal. R refers to a FlightResevation object, butsince R is qualified by Reservation , we may only make use of the gen-eral Reservation properties. It is not possibleto refer to the attributesReservedFlight and ReservedSeat , even though it is known that R de-notes a FlightReservation object, becausethe descriptionof R statesthat R may denotearbitrary Reservation objects. This meansthat it isnot known whether or not R denotesa FlightReservation object or aTrainReservation object.

Consideranassignmentlike:

R[]->F[]

Page 98: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.1 SPECIALIZATION BY SIMPLEINHERITANCE 87

If R denotesa FlightReservation object,thenthis is meaningful. If, how-ever, R denotesa TrainReservation object,this is not meaningful,sinceFis supposedto denoteonly FlightReservation objects.In general,it is notpossibleto infer from thedescriptionof R andF andtheassignmentwhetheror not suchan assignmentis meaningful. Whenthe programis executingitcanbetestedwhetheror not theassignmentis meaningful.In BETA theaboveassignmentis consideredlegal. It may, however, leadto a run-timeerror1 if Rdoesnot referto a FlightReservation object.

Theuseof generalsuper-patternsfor qualifying referencesprovidesgreatflexibility . Moreexampleswill bepresentedlater.

Multi-le vel hierarchies

The classificationhierarchyfor reservationsonly includestwo levels. It ispossibleto model classificationhierarchiesconsistingof an arbitrary num-berof levels,asillustratedby thefollowing example.All Record, Person,Employee, Student andBook objectsmaybeviewedasRecord objects,andthey all have theattributekey . Similarly, Person, Employee and Studentobjectsmay be viewed asPerson objects,andthey all have the Person at-tributeskey , name andsex . This sub-patternhierarchyis illustratedin Fig-ure6.4.

Record: (# key: @integer #);Person: Record(# name: @Text; sex: @SexType #);Employee: Person

(# salary:@integer; position: @PositionType #);Student: Person(# status: @StatusType #);Book: Record(# author: @Person; title: @TitleType #);

Example

Supposethatour travel agency wantsto keepa registerof all reservations.Asimpleversionof sucha registermaybedescribedasfollows:2

ReservationRegister:(# {The reservations are stored in Table[1:top]}

Table: [100] ˆReservation; top: @integer;

Insert: {Insert a reservation into the register}

1In theMjølner BETA Systemthecompilermarksall assignmentsthatrequirea run-timetest.

2Theexample,likemany otherexamplesin thisbook,hasbeensimplifiedto keepit small.In the Insert pattern,it shouldbetestedthat top doesnot exceedTable.range . Similarly,in GetElm it shouldbetestedthat0<inx<=Top .

Page 99: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

88 SUB-PATTERNS

Record

Key

Person Book

Employee Student

Key

Name

Sex

Key

Author

Title

Key

Name

Sex

Salary

Position

Key

Name

Sex

Status

Figure 6.4 Illustrationof sub-patternhierarchy.

(# R: ˆReservationenter R[]do R[]->Table[top+1->top][]#);

NoOfElm:{Return no. of reservations in register}(# exit top #);

GetElm: {Get reservation no. ’inx’}(# inx: @integer

enter inx

Page 100: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.1 SPECIALIZATION BY SIMPLEINHERITANCE 89

exit Table[inx][]#);

#);Reservations: @ReservationRegister

The Reservations register may containinstancesof FlightReservationandTrainReservation . This meansthat reservationsmay be insertedintotheregisterin thefollowing way:

F: ˆFlightReservation;T: ˆTrainReservation;...F[]->Reservations.Insert; ...T[]->Reservations.Insert; ...

In thedescriptionof theReservationRegister patternit is not necessarytoknow whetherit is a train reservationor a flight reservationthatgetsinserted.For thisreason,all referencesin theReservationRegister patternarequali-fiedby Reservation . Also, theReservationRegister patternwill notneedto bechangedif a new kind of reservation is introduced.If our travel agencywantsto extendits businessto handleboatreservations,we could introducea BoatReservation patternasa sub-patternof Reservation , andthustheReservationRegister patternwouldnotneedto bechanged.

Supposethatwewantto find all reservationsmadeby Mr Olsenandinsertthesereservationsinto a specialregistercontainingall reservationsmadebyMr Olsen.Thiscouldbedoneasfollows:

R: ˆReservation; Olsen: ˆCustomerRecord;OlsensReservations: @ReservationRegister...(for i: Reservations.NoOfElm repeat

i->Reservations.GetElm->R[];(if R.Customer[] // Olsen[] then

R[]->OlsensReservations.Insertif)

for)

In this examplewe do not carewhetheror not the reservationsare train orflight reservations,we areonly interestedin reservationsin general.

Testingpattern membership

Suppose,however, that we are interestedin counting the numberof flightreservationsand the numberof train reservations. Then we would needtoknow for eachelementin the register whetheror not it is an instanceof

Page 101: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

90 SUB-PATTERNS

TrainReservation or FlightReservation . Thuswe needto testtheclassmembershipof anobject.Thismaybedoneasfollows:

R: ˆReservation; Olsen: ˆCustomer; NTR,NFR: @integer...(for i: Reservations.NoOfElm repeat

i->Reservations.GetElm->R[];(if R##

// TrainReservation## then NTR+1->NTR// FlightReservation## then NFR+1->NFR

if)for)

The expression R## denotes the pattern of the object referred by R.Similarly, the expression ’TrainReservation##’ denotes the patternTrainReservation . (Rememberthat the expressionTrainReservationwithout ## describesthegenerationof a TrainReservation object.)

Thefirst branchof theif-imperative is takenif theexpression:

R## = TrainReservation##

is true.This is thecaseif R refersto aninstanceof TrainReservation . Simi-larly, thesecondbranchof theif-imperativeis takenif RdenotesaninstanceofthepatternFlightReservation . As we shall seelater, it is rarelynecessaryto usethis form of testing,andit shouldbe avoided,asdemonstratedin thenext chapteron virtual patterns.

6.2 Specializationof actions

Patternsmayalsobeusedto modelconceptswheretheextensionconsistsofsequencesof actions.We have previously referredto suchpatternsasproce-dure patterns.By meansof sub-patternsit is possibleto modelclassificationhierarchiesfor actionsequences.ConsidertheconceptHandleReservation :anelementin theextensionof thisconceptis anaction-sequenceperformedbyan agentwhenmakinga reservation. This conceptmayhave specializationslike HandleFlightReservation andHandleTrainReservation . To modelsuchclassificationhierarchies,it is necessaryto beableto combinetheactionpartof asuper-patternwith theactionpartof asub-pattern.

Considerthefollowing example:

C: (# a,b: @integerdo 11->a;

inner C33->b

Page 102: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.2 SPECIALIZATION OFACTIONS 91

Execution of an instance of C1 starts here

C1: C(# c: @integer do 22->c #)

C: (# a,b: @integer do 11->a; inner C; 33->b #)

OBS. The printed version does not look like the drawingTherefore the arrows have to be placed left to

the position where they should appear

Figure 6.5 Illustrationof inner .

#);

C1: C (# c: @integer do 22->c #)

Instancesof C1 have the attributesa, b, c . The executionof a C1 objectstartsby executionof theimperativesdescribedin C. Eachexecutionof innerC duringtheexecutionof theseimperativesimpliesanexecutionof theimper-ativesdescribedby C1. An executionof a C1 objectimpliesexecutionof:

11->a,22->c and33->b.

illustratedin Figure6.5.Executingan instanceof the C-patternwill result in executionof 11->a ,

followedby 33->b , i.e. executionof inner C is theemptyaction.Theimperative inner C is only legal in thedo-partof thepatternC.Theinner constructis themechanismthatis providedfor specializationof

actions,which maybeobtainedin two ways: asa specializationof theeffectof thegeneralaction,or asaspecializationof thepartiallyorderedsequenceofpart-actionsthatconstitutethegeneralaction.Theinnermechanismsupportsthelatterform of specialization.

Here is anotherexample illustrating the usefulnessof specializationofaction-parts:

Cycle: (#do (Loop: inner Cycle; restart Loop :Loop) #)

TheCycle patternrepeatedlyexecutesaninner-imperative, andmaybeusedasacyclecontrolstructure:

Page 103: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

92 SUB-PATTERNS

...; Cycle(#do Keyboard.get->Screen.put #); ...

This constructis an example of a singular inserteditem. As mentionedin Section 3.1.1, a singular item (object) in the action part correspondsto an anonymousprocedure. The executionof Cycle implies that innerCycle is executedforever. Each execution of inner Cycle implies thatKeyboard.get->screen.put is executed. Of course,it is possibleto exitthebodyof suchacycleby executinga leave:

(# F,G: @Filedo {Open the files F and G}

L: Cycle {Copy F to G}(#do (if F.eos {end-of-stream}

// true then leave Lif);F.get->G.put

#);{Close the files F and G}

#)

It is possibleto furtherspecializeCycle :

CountCycle: Cycle(# inx: @integerenter inxdo inner CountCycle;

inx + 1-> inx ;#);

The CountCycle patternis a sub-patternof Cycle . This hasthe effect thatwhenexecutinganinstanceof CountCycle , its do-partwill alsoberepeatedlyexecuted.TheCountCycle patternis usedin thefollowing evaluation:

...;L: 1->CountCycle

(# F: @integerdo (if inx // 10 then leave L if);

inx->& Factorial->F;{Factorial is computed for inx in [1,9]}

#);...

Theeffectof usingCountCycle maybedescribedby thefollowingevaluation:

Page 104: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.2 SPECIALIZATION OFACTIONS 93

Register:(# Table: [100] ˆRecord;

Top: @integer;

Init: (# ... #);Has: (# key: ˆRecord enter key[] do ... #);Insert: (# ... #);Remove: (# ... #);

ForAll:(# Current: ˆRecorddo (for inx: Top repeat

Table[inx][]-> Current[];inner ForAll

for)#)

#)

Figure6.6 Iteratoron theRegister pattern.

L: 1 ->(# inx: @integer; F: @integer

enter inxdo

(Loop:(if inx // 10 then leave L if);inx->& Factorial->F;inx + 1->inx;restart Loop :Loop)

#)

ThepatternsCycle andCountCycle areexamplesof usingpatternsfor defin-ing controlstructures.Suchpatternswill bereferredto ascontrol patterns.

Specializationof actionsmaybeusedfor makinggeneralcontrolstructurestailoredto specificdatastructures.Figure6.6 describesa new versionof thepatternRegister from Chapter3. The new versiondescribesa registerofRecord objects,andanew patternattribute,ForAll , hasbeenadded.ForAllis a controlpatternwhich scansthroughtheelementsof the register, makingit possibleto stepthroughall the elementsof a Register and perform anoperationuponeachelement,independentlyof how theregisteris represented.

Notice that inner is an imperative, andassuchit maybeusedwhereveran imperative may be used. Theremay also be more than one inner in a

Page 105: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

94 SUB-PATTERNS

descriptor, in whichcasethey will causeexecutionof thesameactions.TheForAll operationmaybeusedin thefollowing way:

...; R.ForAll (# do Current[]->DoSomething #);...

TheconstructR.ForAll(# ... #) is anotherexampleof asingularinserteditem. It hastheForall patternattributeof theobjectdenotedby R asasuper-pattern. Current will thenstepthroughthe elementsof R andeachelementwill one-by-onebeassignedto DoSomething . Sometimesthereis a needfornestingcontrol patterns.In this case,it is inconvenientthat the nameof theindex variablealwayshasto be Current , sincethis makes it impossibletorefer to the index variableof theoutercontrolpattern.This maybechangedby addingthepatternattribute Index to ForAll :

ForAll:(# Current: ˆRecord;

Index: (# exit Current[] #)do ... {As before} ...#)

ForAll maynow beusedasfollows (assumingthatR1 andR2 arereferencesto Register objects):

R1.ForAll(# I: @Indexdo R2.ForAll

(# J: @Indexdo (I,J)->DoMore#)

#)

The attribute I returnsthevalueof Current correspondingto theoutermostcontrol pattern,andJ returnsthe valueof Current correspondingto the in-nermostcontrolpattern.

Shorthand notation for inner

Insteadof inner P it is possibleto write just inner . In thiscase,inner refersto theimmediateenclosingobject-descriptor. Considerthefollowingexample:

PP:(#do (# P: (# ...

do {1} inner PP; ...{2} inner P; ...

Page 106: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.3 ENTER/EXIT-PARTS FORSUB-PATTERNS 95

{3} inner; ...#)

do {4} inner;Cycle(#do {5} inner PP; ... {6} inner; ... #)

#)#)

The inner constructsat 1,2 and 5 are unambiguous,sincethey explicitlyrefer to an enclosingpattern/object-descriptor. The inner at 3 refersdo thepattern/object-descriptorP; the inner at 6 refersto Cycle(# ... #) , sinceitis thenearestenclosingobject-descriptor. This inner will have no effect, asthereis no sub-patternof this descriptor. In general, inner hasno effect ina singular object-descriptor.

6.3 Enter/exit-parts for sub-patterns

Theenter-partof asub-patternis aconcatenationof theenter-partof thesuper-pattern,andtheenter-partspecifiedin thesub-patternandsimilar for theexit-part.Consider:

P: (# ... enter(x,y,z) do ... exit u #);PP: P(# ... enter a do ... exit b #);PPP: PP(# ... enter(n,m) do ... exit(s,t) #)

Thethreepatternshave thefollowing enter- andexit-parts:

Pattern enter-part exit-partP (x,y,z) uPP (x,y,z,a) (u,b)PPP (x,y,z,a,n,m) (u,b,s,t)

In theconcatenationof enter/exit-lists anenter/exit list consistingof a singleelementisconsideredto bealist with oneelement.In theaboveexample,exitu, enter a andexit b areinterpretedasexit(u) , enter(a) andexit(b) .

Considerthespecificationof a patternPoint :

(# Point:(# X,Y: @integer;

move:(# x1,y1: @integerenter(x1,y1)do x1->X; y1->Y; inner#)

enter (X,Y)exit (X,Y)

Page 107: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

96 SUB-PATTERNS

#);P1,P2: @Point;

do ...; P1->P2; ...; (3,14)->P1.move; ...#)

Point objectsareassignable,andwhenassigningonePoint objectto another,thevaluesof X andY aretransferred.

Considermakinga three-dimensionalpoint asa specializationof Point :for suchpointsto beassignable,theextraattributeZ shouldalsobetransferredin anassignment.This is accomplishedby extendingtheenter- andexit-partsof Point by enter/exit of Z. In addition,a sub-patternmove3D of move hasbeenadded:3

(# ThreeDpoint: Point(# Z: @integer;

move3D: move(# z1: @integer enter z1 do z1->Z; inner #)

enter Zexit Z#);

P1,P2: @ThreeDpoint;do ...; P1->P2; ...; (111,222,333)->P1.move3D#)

Instancesof ThreeDpoint have an enter-part and an exit-part of the form(X,Y,Z) . Theenter-partof move3D is (x1,y1,z1) .

6.4 The object pattern

Thereis apredefinedpattern

Object: (# ... do inner #)

which is themostgeneralabstractsuper-pattern.All patternsaresub-patternsof Object . In anobjectdescriptorwithoutasuper-pattern,theObject patternis implicitly assumedto bethesuper-pattern.An objectdescriptorof theform:

(# Decl1; Decl2; ...; Declnenter Indo Impexit Out#)

is interpretedin thefollowing way:3A betteralternativewill beto definemove asa virtual pattern(seeChapter7).

Page 108: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.4 THE OBJECTPATTERN 97

Object(# Decl1; Decl2; ...; Declnenter Indo Impexit Out#)

ThepatternObject hasno attributes. Its action-partconsistsof an inner im-perative. The main purposeof the Object patternis to allow ‘unqualified’references.It is possibleto declarereferenceslike:

R: ˆObject

A referencelike R may refer to any object in a programexecution. Suchareferencecannot,of course,be usedto accessattributesof the objectbeingreferred. It may be usedto executethe objectandto passobject referencesaround.

Restrictionson basicpatterns

As mentionedin Chapter3, therearecertainrestrictionsontheuseof thebasicpatternsinteger , boolean , char and real in the Mjølner BETA System.Onerestrictionis thatthesepatternsarenot sub-patternsof Object .

Anotherrestrictionis that it is not possibleto obtaina dynamicreferenceto instancesof thebasicpatterns.In the following example,codemarkedbyillegal is not acceptedby thecompiler:

X: @integer; {legal}R: ˆinteger; {illegal}

...X[] {illegal}->...

The reasonfor theserestrictionsis efficiency of implementationratherthanany conceptualproblem. It is, however, possibleto get aroundtheserestric-tionsby usingpatternsof theform:

integerObject: (# V: @integer enter V exit V #)

The patternintegerObject is a sub-patternof Object , anddynamicrefer-encescanbeobtainedto suchobjects,asshown in thefollowing example:

X: @integer;Y: @integerObject;Z1,Z2: ˆintegerObject...111->X;

Page 109: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

98 SUB-PATTERNS

P: (# Decl1; Decl2; ... Declnenter Indo Impexit Out#);

P1: P(# Decl’1; Decl’2; ... Decl’menter In’do Imp’exit Out’#);

Figure6.7 Sub-patternDeclaration.

222->Y;Y[]->Z1[];333->Z1;&integerObject[]->Z2[];444->Z2;

Be awarethatanassignmentlike:

333->Z1

is only legal if Z1 is differentfrom NONE.TheMjølnerBETA Systemincludespredefinedpatternslike integerObject .

This is conceptuallynot thebestsolution,but it worksin practice.

6.5 Summary

In this sectiona summaryof the sub-patternmechanismwill be given. Anobjectdescriptormay includea super-pattern(often calledprefix-pattern, orsimply prefix). This specifiesthatobjectsgeneratedaccordingto thedescrip-tion haveall thepropertiesdescribedby thesuper-pattern.

Figure6.7 shows two patterns,P andP1. P1 is an exampleof a patternthathasa super-pattern.Thesuper-patternof P1 is P; P1 is alsosaidto be asub-patternof P. Any P1-objectwill have thesamepropertiesasP-objectsinadditionto thosespecifiedbetween(# ... #) , calledthemain-partof P1.

A P1-objectwill have attributescorrespondingto thedeclarationsDecl1,..., Decln andDecl’1, ..., Decl’m . The enter-part of a P1-objectis a

Page 110: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.6 QUALIFICATIONS AND SCOPERULES 99

concatenationof In and In’ . Theexit-part of a P1-objectis a concatenationof Out andOut’ .

The actionpart of a P1-object is a combinationof Imp and Imp’ . Thiscombinationis controlledby meansof theinner : theexecutionof aP1-objectstartsby executionof the imperative Imp in P. Eachexecutionof an innerduringtheexecutionof Imp impliesanexecutionof Imp’ . If thereis no innerin Imp , thenImp’ will neverbeexecuted.4

In general, the notion of main-part is definedfor patterns,object de-scriptorsand objects: the main-part of a pattern is the part describedbe-tween(# ... #) asstatedabove. The main-partof an objectdescriptorP(# ... #) is thepartbetween(# ... #) . Themain-partof an objectXgeneratedaccordingto adescriptorP(# ... #) is theattributesandactions(includingenter/exit parts)describedby (# ... #) .

6.6 Qualifications and scoperules

Wenow extendthenotionsof qualificationandscoperulesintroducedin Sec-tions3.2.5and5.9to handlesub-patterns.

6.6.1 Qualification

We first extendthe definition of super-patternandsub-patternslightly. Con-siderthepatterndeclaration:

B: A(# ... #)

� ThepatternA is saidto beadirectsuper-patternof B.� A patternP is a super-patternof B if it is a directsuper-patternof B, or if it

is a super-patternof thedirectsuper-patternof B.� ThepatternB is a directsub-patternof A.� A patternP is a sub-patternof B if it is a directsub-patternof B, or if it is a

sub-patternof thedirectsub-patternof B.

Considerthepatterns:

Record: (# ... #);Person: Record (# ... #);Employee: Person(# ... #);

4TheMjølnerBETA Systemcompilerwill givea warningin this case.

Page 111: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

100 SUB-PATTERNS

Here Employee is a sub-patternof both Person and Record . It is a directsub-patternof Person . Similarly, Record andPerson aresuper-patternsofEmployee , while Person is adirectsuper-patternof Employee .

Referenceattributesarequalifiedusingpatternnames.Considera refer-enceattribute,R, declaredasfollows:

R: @Record

or

R: ˆRecord

TheattributeR is saidto bequalifiedby Record .The qualificationof a referencerestrictsthe setof objectswhich may be

referredto by thereference.A referenceattributemaydenoteinstancesof its qualificationor instances

of sub-patternsof its qualification.Consider:

R: ˆRecord;P: ˆPerson;E: ˆEmployee

The referenceR is qualified by Record , and it may refer to instancesofRecord , Person andEmployee . ThereferenceP is qualifiedby Person , andit mayrefer to instancesof Person andEmployee . Finally, E is qualifiedbyEmployee ; it mayonly referto instancesof Employee .

A referencequalifiedby Record may refer to objectsof all the patternsRecord, Person, Employee, Student andBook , while a referencequali-fied by Person mayonly referto Person, Employee andStudent objects.

6.6.2 Scoperules

Thescopeof anattributedeclaredin apatternP includesall sub-patternsof P,i.e. anamedeclaredin P is visible in sub-patternsof P.

A: (# a:...; b:...; c: ...; #);B: A(# d:...; e:...; f: ...

{a,b,c,d,e,f are visible here}#)

Sub-patternscombinedwith a block structuremustalsobe considered.Therule is thatnamesinheritedfrom thesuper-patternsmayhidenamesdeclaredin theenclosingobjectdescriptors:

Page 112: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.7 EXERCISES 101

(# a: ...; d:...; x:...; {1}A: (# a:...; b:...; c: ...; #); {2}B: A(# d:...; e:...; f: ... {3}

{x_1,a_2,b_2,c_2,d_3,e_3,f_3 are visible here}#)

#)

Givena referencedeclaredas:

X: ˆB

all attributesdeclaredin B andin super-patternsof B canbeaccessedremotely,i.e. thefollowing remoteidentifiersarelegal:

X.a X.b X.c X.d X.e X.f

Givena referencequalifiedby Record :

R: ˆRecord

thenonly theattributesof Record , i.e. key , areaccessibleby remoteaccess:

R.key

This is still trueeven if R denotesa Person object,i.e. referencesto Personattributesname andsex of theform:

R.name;R.sex;

areillegal.

6.7 Exercises

(1) RedoExercise3 in Chapter3 usingsub-patterns.

(2) Modify the bankingsystemconstructedin Exercise2 in Chapter 5 tohandlesavings accountsandcheckaccounts.For a savings account,theattributesshouldincludethe interestrateandcalculationof interest.Forcheckingaccounts,the customershouldbe chargeda fee for eachcheckthey write unlessthe balanceexceedsa certainthreshold,in which casewriting checksis free.

Next, modify thebankingsystemsuchthatanownermaybea person,acompany or anorganization(e.g.a soccerclub).

Page 113: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

102 SUB-PATTERNS

(3) Generalizethe sodamachinedevelopedin Exercise5 in Chapter5 bydefininga super-patterncalledVendingMachine . Make a sub-patternofVendingMachine calledCandyMachine , whichis likeaSodaMachine ex-ceptthatinsteadof juiceandcolait provideschewing gum,chocolatebars,etc. Attributescommonto SodaMachine andCandyMachine shouldbedefinedin VendingMachine .

(4) DefineapatternForTo thatexecutesan inner ForTo for eachelementinan interval [first,last] . An integer variableindex holdsthe currentindex value.Thefollowing imperative:

(3,8)->ForTo(#do index->&Factorial #)

shouldcompute3!,4!,...,8! .

Makesimilar DownTo andStepTo patternsthatmaybeusedlike:

(6,2)->DownTo(#do index->&Factorial #){computes 6!,5!,...,2!}

(1,3,8)-StepTo(#do index->&Factorial #){computes 1!,4!,7!}

6.8 Notes

Patternsandsub-patternsgeneralizetheclassandsub-classmechanismfromSimula. Most object-orientedlanguageshave a constructsimilar to the sub-classmechanism;the term inheritanceis often usedfor this. The idea ofspecializingaction-partsby meansof inner alsooriginatesin Simula,whereit is usedfor prefixingof classes.(Vaucher, 1975)proposesto extendthis ideafor prefixingof procedures.In (Thomsen,1987) specializationof processesisfurtherdiscussed.

Oneof thedifferencesbetweenBETA andSmalltalkis thenotionof ‘typ-ing’ objectreferences.In Smalltalkanobjectreferencehasno typeandmayrefer to any object. In BETA an objectreferenceis qualifiedby meansof apatternname.Thequalificationspecifiesthat thereferencemayonly refer toobjectsthathavebeengeneratedaccordingto thatpatternor its sub-patterns.

Testingfor classpatternmembershipas describedin Section6.1 is, bysomepeople,consideredabadprogrammingstyle. In SimulaandSmalltalkitis possibleto performthesetests.In C++ they havebeendeliberatelyleft out,sincethey areviewedasviolating theadvantagesof object-orientation.

Multiple inheritancehascomeupasageneralizationof singleinheritance.With single inheritancea classmay have at most one super-class,whereasmultiple inheritanceallows a classto have several super-classes.Inheritance

Page 114: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

6.8 NOTES 103

is usedfor many purposes,includingcodesharingandhierarchicalclassifica-tion of concepts.In the BETA language,inheritanceis mainly intendedforhierarchicalclassification.BETA doesnot have multiple inheritance,duetothelackof aprofoundtheoreticalunderstanding,andalsobecausethecurrentproposalsseemtechnicallyverycomplicated.

In existing languageswith multiple inheritance,the code-sharingpart ofthe class/sub-classconstructdominates.Flavors hasa namethatdirectly re-flectswhat is going on: mixing someclasses,so the resultingclasshasthedesiredflavor, i.e. the desiredattributes. For the experienceof eatingan icecreamconeit is significantwhetherthevanilla ice creamis at thebottomandthe chocolateon top, or the otherway around.Correspondingly, a classthatinheritsfrom theclasses(A, B) is not thesameasaclassthatinheritsfrom theclasses(B, A).

If, however, multiple inheritanceis to be regardedasa generalizationofsingle inheritance,andtherebyasa modelof multiple conceptclassification(and it shouldbe in the modelpresentedhere),then the orderof the super-classesshouldbeinsignificant.Whenclassifyingaconceptasaspecializationof severalconcepts,thenno orderof thegeneralconceptis implied, andthatshouldbesupportedby thelanguage.

Singleinheritanceis well suitedfor modelinga strict hierarchicalclassifi-cationof concepts,i.e. ahierarchywheretheextensionsof thespecializationsof a givenconceptaredisjoint. Suchhierarchiesappearin many applications,andit is often useful to know that the extensionsof, say, classpredatorandclassrodentaredisjoint.

In classifyingobjectsby meansof differentand independentproperties,several orthogonalstrict hierarchiesmay be constructed.A groupof peoplemaybeclassifiedaccordingto their profession,leadingto onehierarchy, andaccordingto their nationality, leadingto anotherhierarchy. Multiple inheri-tanceis oftenusedfor modelingthecombinationof suchhierarchies.It may,however, be difficult to recognizeif sucha non-stricthierarchyis actuallyacombinationof severalstrict hierarchies.

Page 115: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

104 SUB-PATTERNS

Page 116: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 7

Virtual ProcedurePatterns

Thepattern/sub-patternmechanismmakesit possibleto groupcommonprop-ertiesof patternsinto generalsuper-patterns. This is sufficient as long asthe generalattributesandactionscanbe completelydescribedin the super-pattern. By this we meanthat attributesin a super-patterncanbe describedindependentlyof thesub-patterns.In thetravel agency example,theattributesDate and Customer do not dependon the subpatternsTrainReservationandFlightReservation . This is, however, not alwaysthecase.

Considera patternA with sub-patternsB andC. ThecommonattributesofB andC arelocatedin A, andthe specialattributesfor B andC arelocatedinB andC, respectively. SupposethatbothB andC have anattribute f , andthatthesemanticsof f is similar for B andC. If thedescriptionsof f in B andC areidenticalthenwe canmove thedescriptionof f to A. If, however, thedescrip-tionsof f in B andC arenot identical,thenwe cannotmove thedescriptionoff from B andC to A. Sincef is a propertyof all B andC objects,we would,however, like to describein A thatall sub-patternsof A have an f attribute. Inmany cases,thedescriptionsof f in B andC have a commonstructureandwewould like to move asmuchaspossibleof this commonstructureto A. Thismayappearfairly abstract.Considerthefollowing example.

In caseof the travel agency, it might be useful to display the attributesof a reservation on a computerscreenor print them out on paper. ForTrainReservation we might adda Display attribute thatdisplaysthe val-uesof the attributesDate , Customer , ReservedTrain , ReservedCarriageand ReservedSeat . For FlightReservation we might similarly have aDisplay attributethatdisplaysthevaluesof theattributesDate, Customer,ReservedFlight and ReservedSeat . The propertyof having a Displayattribute is commonto both patterns. In addition, both Display attributesdisplaythe valuesof Date andCustomer . Ideally, suchcommonpropertiesshouldbedescribedin thegeneralReservation pattern.

In this chapterthenotionof virtual patternswill be introduced.By usingvirtual patternsit is possibleto describegeneralpropertiesof apatternattribute

105

Page 117: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

106 VIRTUAL PROCEDUREPATTERNS

in a super-pattern,andto specializethis descriptionin sub-patterns.In thischapterwe introducevirtual patternsusedasprocedures.In Chapter9 theuseof virtual classpatternsis described.Note,however, thatin thesameway thatpatternscanbeusedeitherasclassesor procedures,alsovirtual patternscanbeusedeitherasvirtual classesor virtual procedures.

7.1 Moti vation

In this sectionwe analyzethe exampleof addinga Display attribute to thereservationpatterns.Firstweconsiderthesituationwhereeachof thepatternsTrainReservation andFlightReservation hasa Display attribute:

TrainReservation: Reservation(# ...

Display:(#do Date.Display; Customer.Display;

ReservedTrain.Display;ReservedCarriage.Display;ReservedSeat.Display

#)#);

FlightReservation: Reservation(# ...

Display:(#do Date.Display; Customer.Display;

ReservedFlight.Display; ReservedSeat.Display#)

#);

The dots (... ) indicate the attributes Date , Customer , etc. in the sameway asin thepreviouschapter. We assumethateachof theattributes,Date ,Customer , etc.hasa Display attribute.

As mentionedabove, the propertythat all Reservation objectshave aDisplay attribute is not reflectedin thedescriptionof Reservation . In ad-dition, the two Display attributesboth includethecodefor displayingDateandCustomer .

Before introducinga solution using virtual patterns,we first describeapartial solutionto theproblem. Insteadof onedisplayattributewe have onefor eachpattern.This makesit possibleto describethegeneralpropertiesofthe display attribute in Reservation . In this versionof the Reservationpatternswehave implementeda classificationhierarchyof displaypatterns:

Page 118: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.1 MOTIVATION 107

Reserv$ ation

FlightRes% ervation TrainRes% ervation

DisplayRe& servation

DisplayTrain' Reservation DisplayFlight(Reservation

Figure 7.1 Parallelclassificationhierarchies.

Reservation:(# ...

DisplayReservation:(#do Date.Display; Customer.Display; INNER#)

#);TrainReservation: Reservation

(# ...DisplayTrainReservation: DisplayReservation

(#do ReservedTrain.Display;

ReservedCarriage.Display;ReservedSeat.Display;INNER

#)#);

FlightReservation: Reservation(# ...

DisplayFlightReservation: DisplayReservation(#do ReservedFlight.Display; ReservedSeat.Display;

INNER#)

#)

Theabovepatternsdescribetwoparallelclassificationhierarchies,oneconsist-ing of the reservation patternsandoneconsistingof their displayattributes,illustratedin Figure7.1. The hierarchyof displaypatternsis an exampleofusingthesub-patternmechanismfor specializationof actions,asdescribedinSection6.2.

Considerthereferences:

Page 119: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

108 VIRTUAL PROCEDUREPATTERNS

F: ˆFlightReservation;T: ˆTrainReservation

We caninvoke thecorrespondingdisplaypatternsin thefollowing way:

F.DisplayFlightReservation T.DisplayTrainReservation

As describedin Section6.2,aninvocationof F.DisplayFlightReservationcausesexecutionof thefollowing actions:

(1) Thesuper-patternF.DisplayReservation is invoked.This impliesexe-cutionof

(a) Date.Display

(b) Customer.Display

(c) INNERExecutionof INNER implies:

(2) The main part of F.DisplayFlightReservation is invoked. This im-pliesexecutionof:

(a) ReservedFlight.Display

(b) ReservedSeat.Display

(c) INNER, whichhereis theemptyaction.

At this point, all reservation objectshave a display property. We have de-scribedthegeneralstructureof this propertyusingtheDisplayReservationattribute in the Reservation pattern,andwe have describedthe specializedattributesDisplayTrainReservation andDisplayFlightReservation assub-patternsof DisplayReservation . Thereare,however, someproblemswith this solution:

(1) We have to invent a new namefor the display attribute for eachsub-pattern.

(2) Considera referencequalifiedby Reservation :

R: ˆReservation

Usingthis referencewe mayinvoke thegeneraldisplayattribute:

R.DisplayReservation

Page 120: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.2 DECLARATION OFVIRTUAL PATTERN 109

This will resultin thedisplayof thegeneralreservationattributes.SinceReservation is anabstractsuper-pattern,R shouldreferto aninstanceofTrainReservation or FlightReservation . If R refersto aninstanceofFlightReservation , the invocationR.DisplayReservation will onlydisplaythe generalattributesDate andCustomer . Thespecialflight re-servationattributesReservedFlight andReservedSeat will not bedis-played.

Instead,the display attributesof Reservation and its sub-patternsshouldhave thefollowing properties:

(1) Each of the patternsReservation , TrainReservation and Flight-Reservation should have a patternattribute called Display . WhenDisplay is invoked,theactionsdescribedby DisplayReservation andDisplayTrainReservation or DisplayFlightReservation , respec-tively, shouldbeexecuted.

(2) An invocation

R.Display

should invoke the Display attribute of the object denotedby R. IfR denotesan instanceof TrainReservation , it should invoke theDisplayTrainReservation attributedescribedin theTrainReservationpattern. Similarly, if R denotesan instanceof FlightReservation , itshould invoke the DisplayFlightReservation attribute. (In the the-oretical casethat R denotesan instanceof Reservation , it should ofcoursejust invoke the DisplayReservation attribute describedin theReservation pattern.)

7.2 Declaration of virtual pattern

The above propertiesmay be obtainedby declaringthe Display attributeof Reservation as a virtual pattern,and by extending the descriptionofDisplay in the sub-patternsTrainReservation andFlightReservation .Theresultingreservationpatternsmaybedescribedasfollows:

Reservation:(# ...

DisplayReservation:(#do Date.Display; Customer.Display; INNER#);

Display:< DisplayReservation

Page 121: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

110 VIRTUAL PROCEDUREPATTERNS

#);TrainReservation: Reservation

(# ...DisplayTrainReservation: DisplayReservation

(#do ReservedTrain.Display;

ReservedCarriage.Display;ReservedSeat.Display;INNER

#);Display::< DisplayTrainReservation

#);FlightReservation: Reservation

(# ...DisplayFlightReservation: DisplayReservation

(#do ReservedFlight.Display; ReservedSeat.Display;

INNER#);

Display::< DisplayFlightReservation#)

Theconstruct(calledavirtual patterndeclaration):

Display:< DisplayReservation

is a declarationof a virtual patternattribute called Display . The patternDisplayReservation is thequalificationof thevirtual patternattribute.For anon-virtualpatternattribute,thecompletestructureof thepatternis described.For a virtual patternattribute, its structureis only partially described. It ispossibleto extendthestructureof avirtual patternin sub-patterns.

A virtual pattern may be extended to any sub-patternof its qual-ification, meaning that Display may be extended to sub-patternsofDisplayReservation . Sucha virtual pattern extensionmay be describedin asub-patternof Reservation . Thedeclaration:

Display::< DisplayTrainReservation

statesthattheDisplay patternis extendedto beaDisplayTrainReservati-on. Thequalificationof Display in TrainReservation is DisplayTrain-Reservation . A virtual patternextensionis alsocalledavirtual patternbind-ing, or just binding.

In theFlightReservation pattern,theDisplay is extendedto Display-FlightReservation by:

Display::< DisplayFlightReservation

Page 122: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.2 DECLARATION OFVIRTUAL PATTERN 111

virtualhierarchy.v1

ªª

Date

Reservation

Customer

DisplayReservation

Date

TrainReservation

Customer

DisplayTrainReservation

ReservedTrain

ReservedCarriage

ReservedSeat

Display

Display

Date

FlightReservation

Customer

DisplayFlightReservation

ReservedFlight

ReservedSeat

Display

DisplayReservation

DisplayTrainReservation DisplayFlightReservation

Figure 7.2 Reservationpatternswith virtual Display attribute.

Figure7.2 illustratesthedifferentbindingsof theDisplay attribute.ConsideragainthereferencesT, F andR qualifiedby TrainReservation ,

FlightReservation andReservation , respectively. Invocationof:

T.Display

Page 123: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

112 VIRTUAL PROCEDUREPATTERNS

will invokeDisplayTrainReservation of T. An invocationof:

F.Display

will invokeDisplayFlightReservation of T.It is moreinterestingto consideraninvocationof:

R.Display

Assumethat R refersto an instanceof TrainReservation . From the qual-ification of R we know that R hasa Display attribute. SinceR refersto aninstanceof TrainReservation , the Display attributehasbeenextendedtobetheDisplayTrainReservation pattern,meaningthatR.Display will in-voke DisplayTrainReservation .

If insteadR refersto aninstanceof FlightReservation , R.Display willinvokeDisplayFlightReservation .

Virtual patternattributesprovidegreatflexibility whendescribingsystems.At theplacein theprogramwhereaninvocationlike R.Display takesplace,oneneednotknow theexacttypeof theobjectbeingreferredto, asthatobjectselectstheappropriatepatternattribute.

Considerthereservationregisterfrom theendof Section6.1.Supposethatwe want to displayall the reservationsmadeby Mr Olsen.This canbedonein thefollowing way:

(for i: Reservations.NoOfElm repeati->Reservations.GetElm->R[];(if R.Customer[] // Olsen[] then R.Display if)

for)

Page 124: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.3 DIRECT QUALIFICATION OFVIRTUAL PATTERNS 113

7.3 Dir ectqualification of virtual patterns

In the above exampleit may seeminconvenientto have to introducenameslike DisplayTrainReservation . For this reason,it is possibleto usedirectqualificationof avirtual pattern,whichhasthefollowing syntax:

Reservation:(# ...

Display:<(#do Date.Display; Customer.Display; INNER#)

#);TrainReservation: Reservation

(# ...Display::<

(#do ReservedTrain.Display;

ReservedCarriage.Display;ReservedSeat.Display;INNER

#)#);

FlightReservation: Reservation(# ...

Display::<(#do ReservedFlight.Display; ReservedSeat.Display;

INNER#)

#)

Thevirtual declaration:

Display:<(#do Date.Display; Customer.Display; INNER#)

statesthatDisplay is qualifiedby ananonymouspatternassociatedwith thegivendescriptor. Theextensionof Display in FlightReservation :

Display::<(#do ReservedFlight.Display; ReservedSeat.Display;

Page 125: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

114 VIRTUAL PROCEDUREPATTERNS

INNER#)

states that Display is extended to a new anonymous pattern which isa sub-patternof the anonymous pattern in Reservation . Theseanony-mous patterns have the same structure as the DisplayReservation ,DisplayTrainReservation andDisplayFlightReservation patterns.

7.4 Continued extensionof a virtual pattern

The extensionof a virtual patternattributecanbe continuedat arbitrarylev-elsof sub-patterns.Possiblesub-patternsof, say, FlightReservation mightextendthedisplay attributefurther. In thefollowing example,weshow howthedescriptionof a virtual patternmaybeextendedthroughseveral levelsofsub-patterns.Theexampleusedis theclassificationhierarchyfor records:

Record:(# Key: @integer;

Display:< (#do {Display Key}; INNER #)#);

Person: Record(# Name: @text; Sex: @SexType;

Display::< (#do {Display Name,Sex} ; INNER #)#);

Employee: Person(# Salary: @integer; Position: @PositionType;

Display::< (#do {Display Salary,Position}; INNER #)#);

Student: Person(# Status: @StatusType;

Display::< (#do {Display Status}; INNER #);#);

Book: Record(# Author: @Person; Title: @TitleType;

Display::< (#do {Display Author,Title}; INNER #)#)

Considerreferences:

R: @Record;P: @Person;E: @Employee

Note that thesereferencesdenotepart objects. This meansthat instanceRconstantlydenotesthesameinstanceof Record :

Page 126: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.5 MORE EXAMPLES OFUSINGVIRTUAL PATTERNS 115

� R.Display invokestheDisplay attributedescribedin Record resultinginexecutionof Display Key.

� P.Display invokes the combinationof the Display in Record and theDisplay in Person . This meansthatDisplay Key; Display Name andSex areexecuted.

� E.Display invokesthe combinationof Display asdescribedin Record ,Person and Employee . This meansthat Display Key; Display Nameand Sex; Display Salary and Position areexecuted.

7.5 Mor e examplesof using virtual patterns

In this sectionweprovideadditionalexamplesof virtual patterns.

7.5.1 Specializationof initialization patterns

Virtual patternsareuseful for describingthe initialization of objects. In thefollowing example,thevirtual patternattribute Init maybeusedto initializeinstancesof the patterns.Eachsub-patternlevel extendsthe specificationofInit .

Considera patterndefiningpointobjects:

Point:(# X,Y: @integer;

Init:< (# do 0->X; 0->Y; inner #);#)

Thespecificationof Init indicatesthatit is avirtual pattern.A sub-patternof Point may bind Init to a descriptorthat is a sub-

descriptorof the Init in Point :

ThreeDPoint: Point(# Z: @integer;

Init::< (# do 0->Z; inner #);#)

WhenexecutingtheInit of ThreeDPoint , theactionsof its super-patternareperformed,assigning0 to both X andY. Executionof the inner in Init ofPoint impliesexecutionof theactionsin a possiblesub-pattern;in this case,the assignmentof 0 to Z. In the caseof a ThreeDPoint -object, the innerfollowing 0->Z is an empty action, but in the casewhereThreeDPoint isusedfurtherto define,for example,FourDPoint , thenthe inner wouldcauseexecutionof thespecializedinitializationof FourDPoint .

Page 127: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

116 VIRTUAL PROCEDUREPATTERNS

7.5.2 Computation of salary for differ ent job types

Considera company which hasemployeesworking in four kinds of differ-ent jobs. In two of the job typesthe employeeshave permanentpositions,whereasthey work on an hour-by-hourbasisin the other two job functions.Figure7.3 shows a setof patternsrepresentingthe different job types. ThemostgeneralpatternJob includesa setof attributesfor computingsalary, taxanddeductiblesfor theemployeeperformingthatjob. Thecomputationof taxis thesamefor all jobs,i.e. 45%of thesalaryminusdeductibles.

Thecomputationof salaryanddeductiblesare,however, differentfor thefour job types.Thepatternsfor computingsalaryanddeductiblesarethereforevirtual patterns.Eachemployeehasa standarddeductionof 10000which ishandledin thedefinitionof Deductible in patternJob . NotethatValue is justanauxiliarypattern.In NonPermanentJob anew virtual pattern,hourlyWage ,for computingthehourlywageof theemployee,is defined.

Assumethat the company has100 employees. Staff is a repetitionofreferencesdenotingvariousjob objectscorrespondingto the employees,i.e.Staff[1] maydenoteaninstanceof Job1 , Staff[2] maydenoteaninstanceof Job4 , etc.ThepatternComputeSalarySum computesthesumof all salariesfor all employees.

7.5.3 Geometric figures

Figure7.4 shows a classificationhierarchyof geometricfigures.Supposewewant to develop a computersystemfor handlinggeometricfigures. For allkindsof symbolsit shouldbepossibleto draw thesymbolon a screen,com-putethe areaof the symbol,rotatethe symbol,move the symbol,etc. Mostof thesefunctionscannotbedescribedin a generalsuper-class,but have to bedeclaredasvirtual patterns.We leave it asanexercisefor thereaderto fill inthedetails.

7.5.4 Defining control abstractions

We have previously seenhow sub-patternscanbe usedto definecontrol ab-stractionsusinginner . An exampleof this is theForAll patternin Figure6.6.Thistechniquemaybeusedto defineabstractionsthatcontrolexecutionof oneactionsequenceasexecutedby inner, but otherexamplesof abstractionsneedto control the executionof morethanoneactionsequence.An exampleis acontrolabstractionFind for theRegister pattern.Find searchesfor a givenrecordin theregister:if therecordis found,oneactionsequenceshouldbeex-ecuted;if therecordis not found,anotheractionsequenceshouldbeexecuted.TheFind patternmaybedefinedusingavirtual pattern:

Find:

Page 128: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.5 MORE EXAMPLES OFUSINGVIRTUAL PATTERNS 117

Job:(# name: @text;

Value: (# V: @integer do INNER exit V #);Tax: Value(#do (Salary-Deductible) *45 div 100 ->V #);Salary:< Value;Deductible:< Value(#do 10000->V; INNER#)

#);PermanentJob: Job(# #);NonPermanentJob: Job

(# noOfHours: @integer;Salary::< (# do noOfHours*hourlyWa ge- >V #);Deductible::<(#do 3000+V->V; INNER #);hourlyWage:< Value

#);Job1: PermanentJob

(# Salary::< (#do 35000->V #);Deductible::< (#do 2000+V->V #)

#)Job2: PermanentJob

(# Salary::< (#do 45000->V #);Deductible::< (#do 2500+V->V #)

#);Job3: NonPermanentJob

(# hourlyWage::< (#do 80->V #); (* 80 pr. hour *)#);

Job4: NonPermanentJob(# hourlyWage::< (#do 85->V #); (* 85 pr. hour *)#);

Staff: [100] ˆJob;ComputeSalarySum:

(# Sum: @integerdo 0->Sum;

(for i: Staff.range repeat Staff[i].salary+su m->su m for)exit Sum#)

Figure 7.3 Jobhierarchy.

(# Subject: ˆRecord;NotFound:< Object;index: @integer

Page 129: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

118 VIRTUAL PROCEDUREPATTERNS

GeometricFigure

Circle Polygon

Triangle Parallelogram

Rectangle Rhombus

Figure7.4 Classificationhierarchyfor geometricfigures.

enter Subject[] {The Record to be searched}do 1->index;

Search:(if (index<=Top) // True then

(if table[index][] // Subject[] thenINNER;leave Search

if);index+1->index;restart Search

else NotFoundif)

#)

ThisFind patternmaybeaddedasanattributeto theRegister pattern.Findwill searchfor anelementidenticalto Subject . If suchanelementis foundaninnerwill beexecuted,otherwisethevirtual patternNotFound will beinvoked.

Find maybeusedto implementthepatternHas:

Has: Find(# Result: @boolean;

NotFound::< (#do False->Result #)do True->Resultexit Result#)

Page 130: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.6 BENEFITSOFVIRTUAL PATTERNS 119

(# Expression:(# value:< (# V: @integer do INNER exit V #);#);

Const: Expression(# C: @integer;

value::<(#do C->V #)enter Cexit this(Const)[]#);

BinOp: Expression(# E1,E2: ˆExpressionenter(E1[],E2[])exit this(BinOp)[]#);

Plus: BinOp(# Value::<(#do E1.value+E2.value ->V #) #);Mult: BinOp(# Value::<(#do E1.value*E2.value ->V #) #);

E: ˆExpressiondo {Assign (111+222)*2->E}

((111->Const,222->Co ns t)- >Pl us, 2- >Const )-> Mult- >E[ ];E.value->putInt

#)

Figure7.5 Patternsfor representingarithmeticexpressions.

7.5.5 Arithmetic expressions

Figure7.5showspatternsfor representingarithmeticexpressions.An expres-sion is composedof integer valuesand binary operationssuchas plus andmult. Thevirtual patternvalue computesthevalueof anexpression.

7.6 Benefitsof virtual patterns

Sub-patternsandvirtual patternsarepowerful abstractionmechanisms.Con-sidertheaboveexamplefor computationof salariesand,in particular, thepat-ternComputeSalarySum . Thispatternis independentof theactualjob objects.Theevaluation:

Staff[i].Salary

invokestheSalary patterncorrespondingto theactualjob objectdenotedbyStaff[i] .

Page 131: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

120 VIRTUAL PROCEDUREPATTERNS

Supposethatwe hadto computethesalarywithout usingvirtual patterns.Wewould thenneedsomemechanismto testthejob typeof a job object.Onewayof doingthis is to adda job typeattributeto patternJob :

Job:(# name: @text;

jobType: @integer;...

#)

When creating instancesof Job1 , Job2 , Job3 and Job4 we could thengive jobType the value1, 2, 3 and4, respectively. A (functional) pattern,ComputeSalary , for computingthesalarycould thenbewritten asshown inFigure7.6. In addition,a revisedversionof ComputeSalarySum is included.As canbe seen,it is necessaryto checkthe job type of eachobject in orderto computethecorrespondingsalary. By usingvirtual patterns,thecomputa-tion of salaryis definedtogetherwith eachjob pattern.A (functional)pattern,ComputeDeductible , couldbewritten in asimilar way.

Insteadof introducingtheattributejobType wecouldhaveusedthemech-anismfor testingpatternmembershipas describedin Section6.1. The if-imperativeof ComputeSalary would thenhave thefollowing form:

(if R##// Job1## then ...// Job2## then ...// Job3## then ...// Job4## then ...

if)

The techniqueof usingattributeslike jobType hasbeenshown, sincethis isoftenusedin proceduralprogramminglanguageslikePascalandC.

Perhapsthe most importantadvantageof using virtual patternsappearswhenanew job typeis added.Usingvirtual patterns,we couldadda new jobtypeby defininganew sub-patternof, say, PermanentStaff :

Job5: PermanentStaff(# Salary::< (#do 50000->V #);

Deductible::<(#do 1500->V #)#)

TheComputeSalarySum patternneednot bechanged,sinceit is independentof theactualjob patterns.

Withoutvirtual patternswewouldhaveto makechangesto all patternslikeComputeSalary andComputeDeductible . In general,we recommendusingvirtual patternsin suchsituations.

Page 132: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.7 SUMMARY 121

ComputeSalary:(# R: ˆJob; sum: @integerenter R[]do (if R.jobType

// 1 then (* Job1 *) sum + 35000->sum// 2 then (* Job2 *) sum + 45000->sum// 3 then (* job3 *)

(# S: ˆJob3do R[]->S[]; S.noOfHours*80 + sum->sum#)

// 4 then (* job4 *)(# S: ˆJob4do R[]->S[]; S.noOfHours*85 + sum->sum#)

if)exit sum#);

ComputeSalarySum:(# Sum: @integerdo 0->Sum;

(for i: Staff.range repeat(Staff[i][]->Compu teS al ary )+s um->sum

for)exit Sum#);

Figure 7.6 Functionalpatternfor computingsalary.

7.7 Summary

In this sectiona summaryandfurther detailsof virtual patternsis given. ApatternattributeV of patternP is declaredasvirtual usingoneof theforms:

V1: P: (# V:< Q #)

V2: P: (# V:< Q0(# ... #) #)

V3: P: (# V:< (# ... #) #)

whereQandQ0 arepatternnames.CaseV3 is identicalto caseV2 exceptthatthe object-descriptorfor V is implicitly assumedto have Object asa super-pattern.

ThepatternQ (caseV1), theobject-descriptorQ0(#...#) (caseV2), andtheobject-descriptor(#...#) (caseV3) is calledthequalificationof V.

Page 133: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

122 VIRTUAL PROCEDUREPATTERNS

In an objectdescriptorthat hasP asa super-pattern,the virtual patternVmaybeextendedto objectdescriptorsthataresub-patternsof thequalification.In caseV1 this impliesthatV maybeextendedto sub-patternsof Q; in caseV2V maybeextendedto sub-patternsof Q0(#...#) ; andin caseV3, V maybeextendedto sub-patternsof (#...#) .

So even thoughV may be defineddifferently in differentsub-patternsofP, it is still known in P to be at leasta Q, Q0(#...#) or (#...#) . The ex-tensionsof a virtual patternin differentsub-patternsarethusenforcedto bespecializationsof thedefinitionin thesuper-pattern.

In P-objectsandin instancesof sub-patternsof P with no extensionsof V,the qualificationis the definition of V, so the qualificationis alsoa default-binding.

Thedescriptionof avirtual patternV maybeextendedin sub-patternsof Pby meansof a further binding, which hasoneof theforms:

E1: P1: P(# V::< Q1 #)

E2: P1: P(# V::< Q1(# ... #) #)

E3: P1: P(# V::< (# ... #) #)

The casesE1, E2 andE3 correspondto the casesV1, V2 andV3 in the fol-lowing way:

(1) CasesE1 andE2 candefinea furtherbindingof a virtual patterndefinedasin caseV1, providedthat Q1 is a sub-patternof Q. Q1 doesnot have tobeadirectsub-patternof Q.

(2) CaseE3 canfurther bind a virtual patterndefinedasin casesV1, V2 orV3. The descriptor(#...#) is automaticallymadea sub-patternof thequalificationof V in P.

Q1, Q1(#...#) and (#...#) correspondingto the casesE1, E2 andE3, re-spectively, arecalledtheextendeddescriptor.

In instancesof P1, thepatternV is boundto theextendeddescriptor. LetX be an instanceof P1. Instancesof X.V will be instancesof the extendeddescriptor. This is also the caseif the generationof X.V is specifiedin thesuper-patternP of P1.

A furtherbindingasshown above specifiesthatV is alsoa virtual patternin P1. Thequalificationof V in P1 is its extendeddescriptor. This meansthatV maybefurtherextendedin sub-patternsof P1:

P2: P1 (# V ::< ... #)

It is possibleto extendV by aso-calledfinal binding, whichhasoneof theforms:

Page 134: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.8 EXERCISES 123

F1: P1: P(# V:: Q1 #)

F2: P1: P(# V:: Q1(# ... #) #)

F3: P1: P(# V::(# ... #) #)

A final binding hasthe sameeffect asa further binding, exceptthat V is notvirtual in P1. This impliesthatV maynot befurtherextendedin sub-patternsof P1.

7.8 Exercises

(1) RedoExercise3 in Chapter3 usingvirtual patterns.Includepatternsfordescribingthegeometricfiguresin Section7.5.3.

(2) RedoExercise3 in Chapter6 usingvirtual patterns.

(3) RedoExercise2 in Chapter6 usingvirtual patterns.

(4) Discussthedifferencebetweenspecializationusingsub-patternsandspe-cializationusingvirtual patterns.

7.9 Notes

Theconceptof virtual procedureswasoriginally introducedin Simula.Class,subclassandvirtual procedureareoftenviewedasthemostessentiallanguageconstructsassociatedwith object-orientedprogramming.In Simula,C++ andEiffel, aprocedureattributemayeitherbenon-virtualor virtual, correspondingto patternattributesin BETA beingeithernon-virtualor virtual. In Smalltalk,all procedureattributes(called methods)are virtual. In Chapter9, furtherhistoricalnoteson thevirtual conceptaregiven.

Object-orientedprogrammingdoesnot necessarilyimply late andunsafebinding of names,which is sometimesclaimedto be a weaknessof object-orientedlanguages.As mentionedabove, patternattributesof BETA objectsandproceduresin C++ objectsmaybespecifiedasnon-virtual,which meansthatlatebindingis notusedwheninvoking them.

Whena Smalltalkor Flavorsobjectreactsto a messagepassedto it with‘messagenotunderstood’,it hasnothingto dowith Smalltalkor Flavorsbeingobject-oriented,but with thefactthatthey areuntypedlanguages.

The combinationof qualified (typed) referencesand virtuals in BETAimplies that it may be checked at compile-time that expressionslikeaRef.aMethod will bevalid at run-time,providedof coursethataRef denotesan object. A late binding determineswhich aMethod (of which sub-pattern)will be executed. Which aMethod to executedependsuponwhich object iscurrentlydenotedby aRef .

Page 135: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

124 VIRTUAL PROCEDUREPATTERNS

Considera referenceSomeReservation qualifiedby Reservation . ThismeansthatSomeReservation maydenoteobjectsgeneratedaccordingto thepatternReservation or sub-patternsof Reservation . As Display is de-claredasavirtual in Reservation , it is assuredthat:

SomeReservation.Display

is always valid, and that it will lead to the execution of the appropriateDisplay . However, theuseof untypedreferencesin Smalltalk-like languageshasthebenefitthat recompilationof a classdoesnot have to take the restoftheprograminto consideration.

Whatmakeslatebindingslow is notonly themethodlook-up. If amethodin Smalltalkhasparameters,thenthecorrespondencebetweenactualandfor-mal parametersmustbechecked at the time of execution. Display will, forinstance,have a parametertelling how many copiesto display. This will bethesamefor all specializationsof Display , andshouldthereforebespecifiedaspartof thedeclarationof Display in Reservation .

In BETA this is obtainedby qualifyingvirtuals. ThefactthatDisplay willhaveaparameteris describedby apatternDisplayParameter :

DisplayParameter:(# NoOfCopies: @integerenter NoOfCopiesdo

...#)

Qualifying thevirtual Display with DisplayParameter impliesthatall spe-cializationsof Display in different sub-patternsof Reservation must besub-patternsof DisplayParameter , and thushave the propertiesdescribedin DisplayParameter . This implies that Display in all sub-patternsofReservation will haveanintegerNoOfCopies input-parameter.

If object-orientedprogrammingis to be widely usedin real applicationsprogramming,thentheprovisionof typedlanguagesis amust.As PeterWeg-nersaysin ‘Dimensionsof Object-BasedLanguageDesign’(Wegner, 1987):

‘..., the acceptedwisdom is that strongly typed object-orientedlanguagesshouldbe the norm for applicationprogrammingandespeciallyfor programmingin thelarge.’

As demonstratedabove,it doesnothaveto excludeflexibility in specializationof methodsor latebinding.

Since inheritancehas been introduced by object-orientedlanguages,object-orientedprogrammingis oftendefinedto beprogrammingin languages

Page 136: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

7.9 NOTES 125

thatsupportinheritance.Inheritancemay, however, alsobesupportedby func-tional languages,wherefunctions, typesand valuesmay be organizedin aclassificationhierarchy.

In object-orientedlanguagesinspiredby Smalltalk,classesarespecialob-jectsandinheritanceis definedby amessage-forwardingmechanism.Objectsof sub-classessend(forward)inheritedmessagesthatarenotdefnedby theob-ject to thesuper-class‘object’ in orderto havethemperformed.Thisapproachstressescodesharing: thereshall be only onecopy of the super-class,com-monto all sub-classes.With this definitionof inheritanceit is not strangethat‘distribution is inconsistentwith inheritance’ (Wegner, 1987) andthat ‘Thisexplainswhy thereareno languageswith distributedprocessesthat supportinheritance.’

In themodelof object-orientedprogrammingpresentedhere,themainrea-sonfor sub-classing(specialization)is theclassificationof concepts.Thewayin whichanobjectinheritsamethodfrom asuper-classis – or rathershouldbe– animplementationissue,andit shouldnotbepartof thelanguagedefinition.

Accordingto thedefinitionof patternsandobjectsin BETA givenabove,patternsarenotobjects,andin principleeveryobjectof patternPwill have itsown descriptor. It is left to theimplementationto optimizeby having differentobjectsof P sharethe descriptor. Following this definition of patternsandobjects,thereis no problemin having two objectsof thesamesub-patternactconcurrently, andeven be distributed. The implementationwill in this casesimply make asmany copiesof the patternasneeded,including a possiblesuper-pattern.This doesnot excludethata modificationof thesuper-patternwill haveaneffecton all sub-patterns.

Page 137: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

126 VIRTUAL PROCEDUREPATTERNS

Page 138: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 8

Block Structur e

Compositionis a fundamentalmeansfor organizingobjectsandpatternsintermsof componentsof otherobjectsandconcepts.Therearea numberofdifferentformsof composition,oneof thesebeinglocalization. In BETA, lo-calizationis supportedby meansof block structure, whichwasfirst mentionedin Section5.9. In this chaptertheusefulnessof block structurewill befurtherexplored.Compositionis discussedin generalin Section18.5.2.

A programminglanguagesupportsblock structureif procedures,classesand blocks can be textually nested. BETA supportsblock structuresinceobject-descriptorsmaybearbitrarily nested.This chaptercontainsa numberof examplesof usingblockstructurein theform of nestedpatterns.

8.1 Simple block structur e

Mostobjectdescriptorscontainasimpleform of blockstructure.Oneexampleis thepatternRegister , which hastheform

Register:(# ...

Init: (# ... #);Has: (# ... #);Insert: (# ... #);Remove: (# ... #);

#)

Theobjectdescriptorsfor Init, Has, Insert andRemovearenestedwithintheobjectdescriptorfor Register .

A procedurepatternmayhavelocalprocedurepatterns,asin thefollowingexample:

HandleReservations:{Handle one or more reservations for a customer}

127

Page 139: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

128 BLOCK STRUCTURE

(# GetReservation:{Get reservation request from customer}(# ... #);

MakeReservation:{Perform temporary reservation}(# ... #);

ReleaseReservation:{Release a temporary reservation}(# ... #)

CompleteReservation:{Book desired reservations}(# ... #)

do {Investigate one or more possible reservations }{from customer using GetReservation and }{MakeReservation. Release reservations not used }{and finalize desired reservations using }{ReleaseReservation and CompleteReservation. }

#)

HeretheprocedurepatternHandleReservations hasbeendecomposedintoa numberof simpler procedurepatterns. This decompositionof procedurepatternsinto smallerprocedurepatternsis a usefulstructuringmechanismforlarge procedures.Block structureis useful to provide locality for thesepat-terns.

All theseexamplesshow thenestingof procedurepatterns.We next giveexamplesof nestedclasspatterns.

8.2 Classgrammar

The first exampleof nestedclasspatternsis a patternrepresentingthe con-ceptof a context free grammar. Instancesof the Grammar patternrepresentthe context free grammarof programminglanguagessuchasPascalandSi-mula. A grammarhastheassociatedconceptSymbol , i.e. a grammardefinesthesymbolsof thelanguagebeingdefinedby thegrammar. Dif ferentconcretegrammarshave differentsymbols. Pascalsymbolsdiffer from Simulasym-bols. We would like to reflectthis propertyin the definition of the Grammarpattern;thiscanbedoneusingnestedclasspatterns,asshown in Figure8.1.

An instancerepresentingaPascalgrammarcanbedeclaredasfollows:

Pascal: @Grammar

For this instanceit is possibleto accesstheattributesasusual:

Pascal.noOfRules someText[]->Pascal.Parse->anAST[]

Page 140: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

8.2 CLASSGRAMMAR 129

Grammar:(# noOfRules: @integer;

... {Other attributes for representing a grammar}Parse:<

(# input: ˆtext; output: ˆAbstractSyntaxTreeenter input[]do {Parse the input string according to the grammar}

{and produce an abstract syntax tree}exit output[]#);

Symbol:(# id: @integer; printName: @text; ...

isTerminal: (# ... exit aBoolean #);#);

#)

Figure8.1 Grammarpattern.

The patternSymbol may be usedto declarePascalsymbolsin the followingway:

A,B: @Pascal.Symbol

UsingA andB, it is possibleto accessattributesdescribedin theSymbol pat-tern:

A.printName B.isTerminal -> aBool

Consideranothersetof instances:

Simula: @Grammar; X,Y: @Simula.Symbol

Pascal and Simula are both instancesof the samepatternGrammar. TheobjectsA,B andX,Y are,however, not instancesof thesamepattern;A,B areinstancesof the patternPascal.Symbol , whereasX,Y are instancesof thepatternSimula.Symbol . Intuitively, thisis whatwewant,sinceA,B arePascalsymbolsandX,Y areSimulasymbols.Thetwo classesof symbolsareclearlydifferent.

ThedifferencebetweenPascal.Symbol andSimula.Symbol is thesameasthedifferencebetweenPascal.Parse andSimula.Parse . Thelatter twoexpressionsinvokedifferentParse instances,sincethey havedifferentorigins.Figure8.2showsa diagramrepresentingtheobjectsPascal andSimula .

Page 141: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

130 BLOCK STRUCTURE

Pascal

Move

noOfRules

Grammar Grammar

112

Symbol

struc (# ... #)

origin

Parse

struc (# ... #)

origin

struc (# ... #)

origin

struc (# ... #)

origin

Simula

Move

noOfRules 125

Symbol

Parse

Figure8.2 Diagrammaticrepresentationof Grammar objects.

Pascal

Move

noOfRules

Grammar Grammar

112

Symbol

Parse

Simula

Move

noOfRules 125

Symbol

Parse

origin

isTerminal

printName

id 18

if

origin

isTerminal

printName

id 25

do

origin

isTerminal

printName

id 59

class

origin

isTerminal

printName

id 23

if

Symbol Symbol Symbol Symbol

Figure8.3 Diagrammaticrepresentationof Grammar andSymbol objects.

Figure8.3showstheobjectsPascal , Simula , A,B,X andY. NotethatA,BandX,Y have differentorigins. Thestructurereferencesfor Parse, Symbol

Page 142: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

8.3 FLIGHT RESERVATION EXAMPLE 131

andisTerminal havebeenomitted.By declaringSymbol local to theGrammar pattern,wehave thepossibility

of distinguishingbetweensymbolsof differentgrammars.Also,sincetheclassSymbol is local to Grammar, a symbolhasno existencewithout a grammar.Fromamodelingpointof view, this is whatwewant.

In the exampleabove the staticreferencesA,B,X andY denotestaticob-jects.It is, of course,alsopossibleto declaredynamicreferenceslike:

C: ˆPascal.Symbol; Z: ˆSimula.Symbol

The referenceC may denoteany instanceof Pascal.Symbol andZ any in-stanceof Simula.Symbol . Supposethatwe want to declarea referencethatcandenotearbitrarysymbols.This canbedoneby declaringadynamicrefer-encequalifiedby Grammar.Symbol :

S: ˆGrammar.Symbol

Note the differencefrom the declarationof A usingPascal.Symbol , wherePascal is a referenceto a Grammar object. In thedeclarationof S, Grammaris a patternname. S can refer to instancesof either Pascal.Symbol orSimula.Symbol . In fact, the patternGrammar.Symbol may be viewed asa generalizationof the patternsPascal.Symbol and Simula.Symbol . TheGrammar.Symbol patternis thena representationof thegeneralconceptof asymbolof acontext freegrammar.

8.3 Flight reservation example

In thissectionwemakeuseof nestedclasspatternsto furtherextendthetravelagency example.TheFlightReservation patterncontainsanattributedec-laration:

ReservedFlight: ˆFlight

We now considerhow to describethepatternFlight , but beforedoingsoweneedto understandtheconceptof aflight.

Considertheflight tableof Scandinavian Airline Systems(SAS).This ta-ble containsa descriptionof variousentriesSK273,SK451,SK511,etc.,cor-respondingto thevariousroutesservedby SAS.An entrylikeSK273containsinformationaboutthe sourceanddestinationof the route,andotherproper-tiessuchasdeparture,arrival andflying timesaregiven. It seemsobvioustorepresenttheseentriesasinstancesof a patternrepresentingtheconceptof aflight entry.

For our flight reservation systemmore objectsare needed. The flightSK451betweenCopenhagenandLos Angelesactuallytakesplacemostdaysof theyear. A tablefor handlingreservationsmustcontainanentry for each

Page 143: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

132 BLOCK STRUCTURE

FlightType:(# source, destination: ˆCity;

departureTime,arrivalTime: @TimeOfDay;flyingTime: @TimePeriod;

Flight:(# Seats: [NoOfSeats] @Seat

actualDepartureTime ,actualArrivalTime: @TimeOfDay;actualFlyingTime: @TimePeriod;

DepartureDelay:(#exit(actualDepartu reT ime - departureTime)#)

#);

DisplayTimeTableEnt ry: (# ... #);...

#)

Figure8.4 TheFlightType pattern.

day theflight takesplace. Eachsuchentryshouldincludeinformationaboutseatreservationsfor thatday, etc.For aflight entrylikeSK451,wecanincludeaconceptthatclassifiesall flightscorrespondingto SK451.

Patternsrepresentingflight entriesand actualflights are shown in Fig-ure8.4.

The FlightType patternis supposedto be usedfor modelingentriesina flight timetable. For eachentry in the timetablethereis an instanceof theFlightType pattern;suchinstancesrepresentflight entrieslike SK451 andSK273. A FlightType objectincludesinformationaboutsource,destination,departuretime,arrival time,flying time,etc.

Page 144: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

8.3 FLIGHT RESERVATION EXAMPLE 133

TimeTable90: @(# ...

SK451: @FlightType;SK273: @FlightType;

...Init:<

(# ...do ...

’Copenhagen’ -> SK451.source;’Los Angeles’ -> SK451.destination ;...

#)#);

ReservationTable90: @(#

SK451Flights: [365] ˆTimeTable90.SK45 1.F lig htSK273Flights: [365] ˆTimeTable90.SK27 3.F lig ht

...#)

Figure 8.5 PatternsTimeTable andReservationTable .

An attribute like departureTime is actuallymodelingthe scheduledde-parturetime, which may vary from day to day. A table for handlingreser-vationsmustcontainan entry for eachday the flight takesplace. Eachsuchentryshouldhave informationaboutthereservationof seatsfor thatday, andit might includeinformationaboutthe actualdeparturetime, etc. in ordertocomputevariouskindsof statistics.EachFlightType objecthasa local classpatternFlight , which modelstheactualflights takingplace.Instancesof theFlight patternhave attributescharacterizinga givenflight, including a rep-etition of Seat objects,theactualdeparturetime, theactualarrival time, andtheactualflight time.

Objectsrepresentingthe timetableandthe reservation tablefor 1990areshown in Figure8.5. NotethatSK451Flights is a repetitionof referencestoinstancesof theclassFlight patternof theobjectdenotedby SK451, whereasSK273Flights denotesinstancesof the Flight patternattribute of SK273.Theactualflight SK451 takingplaceat dayno. 111of year1990is thusmod-eledby theobjectdenoted:

ReservationTable90.SK451Flights[1 11]

Seatno. 48 for theflight of thatdaymaythenbereservedby executing:

Page 145: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

134 BLOCK STRUCTURE

ReservationTable90.SK451Flights[ 111].S eats[ 48].R eserv e

assumingthat Seat objectshave a Reserve attribute. When the flight hastaken place,the actualtimesfor departure,arrival andthe flight time canbeenteredinto theflight object.Thedifferencebetweentheestimatedflight timeandtheactualflight timecanbecomputedby executing:

ReservationTable90.SK451Flights[ 111].D epart ureDe lay

whichreturnsthedifferencebetweenactualDepartureTime anddepartureTime .Note that DepartureDelay refers to the global referencedepartureTimein the enclosingFlightType object. This would not have beenpossibleif Flight were not definedlocally to FlightType . In the exampleabove,Flight is a classpatternattributeof FlightType . In addition,FlightTypeinstanceshave the referenceattribute destinationand the procedurepatternattribute DisplayTimeTableEntry . For the different instancesSK451 andSK273 of the FlightType pattern,the attributesSK451.destination andSK273.destination are different attributes. Also, SK451.DisplayTime-TableEntry and SK273.DisplayTimeTableEntry are different procedurepatterns,sincethey areattributesof differentinstances.In thesameway, theclasspatternsSK451.Flight andSK273.Flight aredifferent,sincethey areattributesof differentFlightType objects.

8.4 Exercises

(1) Write apatternDocument with thefollowing properties:

(a) A documentis a sequenceof charactersnumberedfrom 1.

(b) It is possibleto defineoneor moreselectionsin adocument.A selec-tion identifiesaninterval of thecharactersin thedocumentincludingapositionbetweentwo characters.A selectionshouldberepresentedby a Selection object.

(c) A documenthas a current selection which is a referenceto aSelection object.

(d) Text canbeinsertedby replacingthecharactersidentifiedby thecur-rentposition.

(e) Thetext identifiedby thecurrentselectioncanbedeleted.

(f) Thereis adistinguisheddocumentcalledClipboard .

(g) A Selection objecthasthefollowing operations:� Copy whichcopiestheselectedtext to theClipboard .� Cut which deletes the selected text and stores it on the

Clipboard .

Page 146: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

8.5 NOTES 135

� Paste which replacesthe selectedtext with the text on theClipboard .

(h) A Selection objectis createdby giving aninterval to a document.

(i) The current selectionmay be replacedby a referenceto anotherSelection object.

DefinethepatternSelection asa localpatternof Document .

(2) Write a HyperText patternwith thefollowing properties:

(a) A hypertext consistsof asetof links.

(b) A link consistsof a sourceanda destination,eachbeinga referenceto ananchorof adocument.

(c) A hypertext hasan operationdefinelink which takesa source-anddestinationanchorasparameters.

(d) It hasanoperationfor scanningall links.

Use the Document patternof the previous exerciseand the Selectionpatternfor representingtheanchorconcept.

8.5 Notes

Block structurewasfirst introducedin the Algol-60 programminglanguage.An Algol block correspondsto an object descriptorin BETA. The purposeof this chapterhasbeento show thatblock structureasfound in SimulaandBETA, but abandonedin Smalltalk-80,is a naturalandpowerful mechanism.Whenmodelingphenomena,it is useful to be ableto characterizean objectby meansof a class. In addition,block structureis useful for a numberoftechnicalproblemsin programming.

Block structureis not theonly way in which SimulaandSmalltalkdiffer.SimulacontainsAlgol-60 asasubsetandsupportsblockstructure,static(lex-ical) namebinding,andcompile-timetypechecking,but Smalltalkhasnoneof thesefeatures. Smalltalk is more in the style of Lisp, with a flat set ofdefinitions(classes),dynamicnamebindingandrun-timetypechecking.

TheSchemelanguageis anexampleof a Lisp dialectwith blockstructureandlexical namebinding.

In Simulatheuseof nestedclassesis limited by a numberof restrictions.BETA doesnothave theserestrictions.

Block structureis a controversialsubjectthathasgivenrise to muchdis-cussionin theliterature.In whatfollowswe commenton this discussion.� Locality. The major advantageof block structureis locality. This makes

it possibleto restrict the existenceof an object and its descriptionto theenvironment(object)whereit hasmeaning.

Page 147: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

136 BLOCK STRUCTURE

� Scoperules. Thereare (at least)the following aspectsof scoperules fornamesdeclaredwithin anobject:

– They only exist whentheobjectexists.Thisis aconsequenceof locality.– Accessto globalnamesandredeclarationof names.

Global names may or may not be seen within a block. In(Wulf andShaw, 1973) it is argued that the use of global variableswithin nestedblocks is a sourceof errors. It is considereda problemthata namecanberedeclaredwithin an internalblock. Thereis, how-ever, noreasonto allow suchredeclarationin a languageif it is foundtobeaproblem.Also, it hasbeenargued that it may be difficult to seewhich globalnamesarebeingusedwithin an internalblock. Again, this is not in-herentlytied to block structureandcanbe avoided. In languageslikeEuclid((Lampsonet al., 1977)), ablockmustexplicitly import from theenclosingblockall namesbeingused.

– Accessto nameswithin a block from ‘outside’ the block may be re-stricted. The hidden/protectedmechanismof Simulais an exampleofthis.

� Syntax. In (Hanson,1981) it is saidthat:

‘Block structurecanmake evenmoderatelylarge programsdif-ficult to read. Thedifficulty is dueto thephysicalseparationofprocedure-headingsfrom theirbodies....’

In (Tennent,1982) it is demonstratedthatthis is merelya matterof syntax.By usingthe syntaxfrom Landin’s ISWIM it is possibleto placeinternalproceduredeclarationsafterthebodyof theblock.

In thedesignof BETA, theabove-mentionedproblemswereconsideredminor.The reasonis that in BETA block structureis not a mechanismintendedfor‘programmingin thelarge’. Block structureshouldbeusedfor ‘programmingin thesmall’. In languagessuchasAlgol-60 andPascal,whereblockstructureis theonly structuringmechanism,theaboveproblemsmaybemoreserious.

Thegrammarexampleis inspiredby (Liskov andZilles, 1974), whomakeuseof abstractdatatypesin the CLU language.SinceCLU doesnot haveblockstructure,theSymbol classis declaredoutsidetheGrammar class,whichgives problemswith restricting the implementationdetails of the Grammarclass. For a discussionof these problems see (Liskov andZilles, 1974;Madsen,1987)

The flight reservation exampleis often describedasan instanceof whatis calledthePrototypeAbstractionRelationProblemasformulatedby BrianSmith(Smith,1984). Theproblemis thataflight entrancelike SK471(a pro-totype)maybeviewedasaninstanceof theclassof flight entriesandalsoas

Page 148: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

8.5 NOTES 137

aclasswhoseinstancesaretheactualSK471flights. To modelthis it is neces-saryto beableto describeSK471bothasanobjectandasa class.This is notpossiblein languageslike Smalltalk. Themetaclassmechanismof Smalltalkcando someof this, but is not generalenough.TheBETA solutiondescribesSK471asanobjectwith a classattribute.

Page 149: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

138 BLOCK STRUCTURE

Page 150: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 9

Virtual ClassPatterns

Virtual patternsareusedto describethecommonstructureof patternattributesin a super-pattern.In Chapter7 thenotionof virtual patternswasintroducedby meansof virtual procedurepatterns.In this chapter, thevirtual conceptisfurtherexploredby giving examplesof virtual patternsusedasclasses.

In BETA thereis no technicaldifferencebetweenprocedurepatternsandclasspatterns,it is simply a matterof how instancesaregenerated.For pro-cedurepatterns,instancesare generatedin the action-partand immediatelyexecuted.The instancethenbecomesinaccessiblesinceno referenceto it issaved. For classpatterns,‘named’ instancesaregeneratedin thesensethatareferenceto theinstanceis saved.

9.1 Dir ectly qualified virtual classpatterns

As alreadymentioned,the specificationof a virtual classpatternis identicalto the specificationof a virtual procedurepattern– the differenceis in howinstancesaregenerated.ConsiderFigure9.1: the classGraph hasclassat-tributesNode andLink which definetheelementsof a graph.Node andLinkarespecifiedasvirtual classes.Subclassesof Graph may extendthe defini-tions of Node andLink correspondingto specificdifferentkinds of graphs.Instancesof Node will thereforealwayshave theattributeConnected , andin-stancesof Link will have theattributesSource andDest . As canbeseen,thevirtual procedureConnect makesuseof theseattributes.

NotethattheNode classesin two differentinstancesof Graph aredifferentclasses,as they areattributesof differentobjects. A Node object from oneGraph objectcannotbecomepartof anotherGraph .

In theDisplayableGraph subclass,thedefinitionsof Node andLink havebeenextended.This is reflectedin theextendeddefinitionof Connect whichhasanadditionalparameterDL. Theexecutionof Connect impliesthegenera-tion of a Link object(&Link ). ThisLink objectis aninstanceof theextendedLink class,andthereferenceL denotesthis instance.ThusL.DispLine is a

139

Page 151: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

140 VIRTUAL CLASSPATTERNS

Graph:(# Node:< (# Connected: @boolean #);

Link:< (# Source, Dest: ˆNode #);Root: ˆNode;Connect:<

(# S,D: ˆNode; L: ˆLinkenter(S[],D[])do &Link[]->L[];

S[]->L.source[]; D[]->L.Dest[];true->S.Connected-> D.Connec ted ;INNER

#);#);

DisplayableGraph: Graph(# Node::< (# DispSymb: ˆDisplaySymbol #);

Link::< (# DispLine: ˆDisplayLine #);Connect::<

(# DL: ˆDisplayLineenter DL[]do DL[]->L.DispLine[] ; INNER#);

Display:< (# .... #)#);

TravellingSalesma nGraph : Graph(# Node::< (# Name: ˆText #);

Link::< (# Distance: @integer #);Connect::<

(# D: @integerenter Ddo D->L.Distance; INNER#);

#);DG: ˆDisplayableGraph;TG: ˆTravellingSalesman Graph

Figure 9.1 Exampleof virtual classpatterns.

valid expression.The referenceDG.Root is known to denotean instanceoftheextendedNode class,thusanexpressionlikeDG.Root.DispSymb is valid.

The definition of TravellingSalesman is similar, but with differentex-tensionsof Node, Link andConnect .

Page 152: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

9.2 GENERAL PARAMETERIZED CLASSPATTERNS 141

9.2 Generalparameterizedclasspatterns

In thepreviouschapterstherehavebeenexamplesof patternsdescribingregis-tersfor insertingvariouselements.TheRegister in Chapter3 maybeusedtostoreinteger objects;theReservationRegister patternin Chapter6 maybeusedto storeReservation objects.Thesepatternshaveasimilarstructure:the main differenceis the type of elementsthat canbe insertedin a register.From a modelingpoint of view, it is desirableto be ableto describea gen-eralgenericRegister patternwhich canbeusedto insertarbitraryelements.Specialregistersrestrictedto reservationsor recordscouldthenbedefinedassub-patternsof this generalRegister pattern.

TheRegister patternin Figure9.2isanexampleof suchageneralpattern.Theonly maindifferencefrom thepreviousregisterpatternsis thevirtual classattributeContent . Content is thetypeof theelementsof theRegister , andis qualifiedby themostgeneralObject pattern.This meansthata Registerobject may include instancesof all patterns. Note that the qualificationofContent is describedusinga patternname– mostexamplessofar have usedtheform of directqualificationof virtual patterns.

In sub-patternsof Register it is possibleto restrictthetypeof elementstobestoredin theregister. Figure9.3showsanexampleof a registerfor storingRecord objects.The RecordRegister patternis definedasa sub-patternofRegister , wherethequalificationof thevirtual classpatternis extendedto theRecord pattern.Thismeansthattheelementsof theregistermustbeinstancesof Record or sub-patternsof Record .

A Display attribute hasbeenaddedto RecordRegister . The virtualpatternDisplay scansthroughall the elementsof the setand invokestheirDisplay pattern.This is possibleasall elementsin theregisterareknown tobe instancesof Record or its sub-patterns.Suchobjectsall have a Displayattribute.

It is possible to make further sub-patternsof RecordRegister . AStudent registercanbe declared,as in Figure9.4, whereall objectsin thisregisterareStudent objects.Herewe havemadeafinal bindingof Content ,which meansthat it is not possibleto make further restrictionsof thequalifi-cationof Content in sub-patternsof StudentRegister .

Page 153: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

142 VIRTUAL CLASSPATTERNS

Register:(# Content:< Object;

Table: [100] ˆContent; Top: @integer;Init:< (# ... #);Has: Find

(# Result: @boolean;NotFound::(#do false->Result #)

do true->Resultexit Result#)

Insert:(# New: ˆContententer New[]do (if (New[]->Has) // false then ... if)#);

Remove: (# ... #);ForAll:

(# Current: ˆContentdo (for inx: Top repeat

Table[inx][]->Curre nt [];INNER

for)#);Find:

(# Subject: ˆContent; index: @integer;NotFound:< Object

enter Subject[]do 1->index;

Search:(if (index<=Top) // true then

(if Subject[] // Table[index][] thenINNER;leave Search

if);index+1->index;restart Search

else &NotFoundif)#);

#)

Figure 9.2 TheRegister patternparameterizedwith virtual patterns.

9.3 Notes

Even thoughthe mostcommonuseof redefinitionsof virtuals (methods)isto reflectspecialization,mostobject-orientedlanguageswith virtuals do not

Page 154: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

9.3 NOTES 143

RecordRegister: Register(# Content::< Record;

Init::< (# ... #);Display:<

(#do ForAll(#do Current.Display #); INNER#)

#)

Figure 9.3 Sub-patternof Register .

StudentRegister: RecordRegister(# Content:: Student;

UpdateStatus: Find(# Status: @StatusType;

NotFound:: (# ... #)enter Statusdo Status->Table[index] .S tat us#)

#)

Figure9.4 Exampleof aspecializationof theRegister pattern.

requiredefinitionsof virtuals in sub-classesto be specializationsof the vir-tual definitionsin the super-class.A sub-classmethodin SmalltalkandFla-vorsneednothavemorethantheidentifierin commonwith thecorrespondingmethodin thesuper-class.A recentimprovementof Simulahasmadeit possi-ble to specifytheparametersthatall proceduredefinitionsin sub-classesmusthave, but apartfrom that,a definitionof a virtual in a sub-classconsistsof apureredefinitionof thevirtual definitionin thesuper-class.

In theuseof theselanguagesit has,however, beenrecognizedthata pureredefinitionof thevirtual is not alwayswhat is wanted.When(re)definingavirtual in asub-class,thedefinition(or effect)of thevirtual in thesuper-classissometimesneeded.In Smalltalkthis is obtainedby simplysendingamessageto thesuper-class(from within themethodof thesub-class),sothatthemethodof thesuper-classis performed,i.e. theoppositeof inner . Flavorsprovidesa moresophisticatedscheme(e.g. beforeandafter methods).In Simulathevirtual definitionin thesuper-classis simply not accessibleaspartof or aftera bindingof thevirtual.

Page 155: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

144 VIRTUAL CLASSPATTERNS

In thecasewherepatternattributesareusedto generateandexecuteitemobjects, they correspondto local proceduresin Simula and to methodsinSmalltalkandFlavors.AsBETA hasageneralsub-patternconcept,alsocover-ing itemobjectsactingaslocaloperations,wehavein Smalltalkterms‘classesandsub-classesof methods.’ It is not a new idea to usethe class/sub-classmechanismfor methods. In 1975Vaucherproposedprefixed proceduresasa structuringmechanismfor operations (Vaucher, 1975). In BETA this is aconsequenceof a moregeneralnotionof pattern/sub-pattern.As Vaucherhasdemonstrated,aclass/sub-classmechanismfor methodsis usefulin itself.

The essenceof specializationby sub-patternsis that objectsof a sub-patternof a patternP shouldhave all the propertiesof P-objects. Thereis,however, no way to guaranteethis, sincea sub-patternmayintroduceproper-tiesthat‘contradict’ theintentionsof thesuper-pattern.

Languagessupportingclasses/sub-classesdo not prevent programmersfrom makingsuchsub-classes,although,by default,objectsof sub-classesbe-have like objectsof thesuper-class.Oneexampleof this is thatanobjectof asub-classinheritstheattributes(in termsof variablesandprocedures/methods)of the super-class. The term inheritanceis very often usedinsteadof sub-classing.This reflectsthe fact that inheritanceof ‘code’ is often consideredto be the major benefitof sub-classing.In BETA, sub-classingis primarilyconsideredamechanismfor modelingconceptualhierarchies,althoughit maybeusedfor codesharingaswell. This is oneof themajordifferencesbetweenthe Americanandthe Scandinavian schoolsof object-orientedprogramming(Cook,1988).

Page 156: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 10

Part Objects and ReferenceAttrib utes

Classificationandcompositionarefundamentalmeansfor apprehendingthereal world. Classificationis the meansby which we form and distinguishbetweendifferent classesof phenomenaand concepts. Compositionis themeansby which we understandphenomenaandconceptsasa compositionofotherphenomenaandconcepts.

In thepreviouschapterswe haveseena numberof examplesof usingpat-terns,sub-patternsandvirtual patternsfor supportingclassification.In Chap-ter 8 we have seenhow nestedpatterns(block structure)maybeusedto sup-port localization,which is oneform of composition.In this chapterwe shalltakeacloserlook atpart-objectswhichsupportsanotherform of compositioncalledwhole-partcomposition. This form of compositionis usefulfor struc-turing phenomenainto wholesandparts.Themodelingaspectsof whole-partcompositionarementionedin Chapter2, andarefurther discussedin Chap-ter 18 (Section18.5.2).In this chapterwe shallgivea numberof examplesofusingpart-objectsin BETA to modelwhole-partcomposition.

We alsogive examplesof how to use(dynamic)referenceattributesforsupportingreferencecomposition, which is a third form of composition.Ref-erencecompositionis alsodiscusedin Section18.5.2.

10.1 Part objects

The constructfor declaringa part objectwas introducedin Chapter3. Thestick figure from Figure 2.3 may be describedin BETA, as shown in Fig-ure 10.1. In additionto thepartsof Figure2.3, operationsfor graphicalani-mationof astick manhavebeenadded.It is possibleto move,draw andcleara stick manon a screen,andit is possibleto wave thehandsandwriggle thetoes.An instanceof astickmanmaybedeclaredin thefollowing way:

145

Page 157: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

146 PART OBJECTSAND REFERENCEATTRIBUTES

StickMan:(# theHead: @Head;

theBody: @Body;LeftArm,RightArm: @Arm;LeftLeg,RightLeg: @Leg;move: (# ... #);draw: (# ... #);clear: (# ... #);...

#);Head: (# ... #);Body: (# ... #);Arm: (# theHand: @Hand; ... #);Leg: (# theFoot: @Foot; ... #);Hand: (# wave: (# #); ... #);Foot: (# bigToe: @Toe; ... #);Toe: (# wriggle: (# #); ... #)

Figure10.1 PartialBETA descriptionof astickman

Joe: @StickMan

ThestickmanJoe maybemanipulatedin thefollowing way:

Joe.move;Joe.wave;Joe.LeftLeg.theFoot.bigToe.wriggl e

The move operationmay be implementedby invoking a correspondingmoveoperationon theparts:

move:(# pos: @pointenter posdo pos->theHead.move; pos->theBody.move;

pos->LeftArm.move; pos->RightArm.move;pos->LeftLeg.move; pos->RightArm.move;

#)

Clear anddraw maybeimplementedsimilarly.Operationsof a compoundobjectareoftencomposedfrom operationsof

its partobjects.An exampleof this is themove operation,which is definedasa compositionof move operationson theparts.Themove operationillustratesthatwhole-partcompositionis alsorelevantfor action-sequences.

Page 158: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

10.1 PART OBJECTS 147

A StickMan is alsocharacterizedashaving anoperationfor wriggling theleft big toe.In contrastto themove operation,nooperationfor thisis definedasanattributeof StickMan . Instead,thewriggle operationof thebigToe partisuseddirectlyusingthenotationJoe.LeftLeg.theFoot.bigToe.wriggle .

A compoundobjectmay thusbe characterizedby having operationsthatinvokeoperationsof its partsandby operationsdefinedin its parts.

In somesituationsit may be more convenient to ‘propagate’an opera-tion of a part to thewholeobject. Thewriggle operationmay, for example,bepropagatedto theStickMan objectby definingthefollowing operationofStickMan :

LeftBigToeWriggle: (#do LeftLeg.theFoot.BigToe.wriggle #)

Notethat if all thetentoescanwriggle, thentensuchoperationsmayhave tobedefined.

10.1.1 Independentand dependentparts

The above exampleshows that a compoundobjectmay directly usean op-erationof its partsor it may defineoperationswhich control its parts. Thepartsareindependentof thewholeobjectin thesensethat they areinstancesof patternsdefinedwithout knowledgeaboutbeingpartof someotherobject.In somesituationsit maybedesirablethat thedefinitionof a parthasknowl-edgeaboutthe compoundobject. This is possibleby placingthe definitionsof thepatternsinsidethewholeobject.By doingthis it is possibleto refer toattributesof thewholeobjectfrom theparts.

In thissectionweshallshow how it is possibleto usevirtual patternsto de-fine partobjectsthatreferto thewholeobject.Considerthefollowing patterndefininganaddress:

Address:(# Street: @text;

StreetNo: @integerTown,Country: @text;printLabel:<

(#do INNER;

{print Street, StreetNo, Town, Country};#)

#)

In this definitionof anAddress , it is not decidedwhetheror not it is thead-dressof aperson,company, organization,etc.For thisreason,theprintLabeloperationhasbeenmadevirtual. In theexamplesbelow it is shown how theAddress patternmaybeusedto defineaddressesof personsandcompanies:

Page 159: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

148 PART OBJECTSAND REFERENCEATTRIBUTES

Person:(# name: @text;

adr: @Address(# printLabel::<(#do {print name} #);#);

Company:(# name,director: @text;

adr: @Address(# printLabel::<(#do {print name and director} #);

#);

The addresspart of Person objectsis definedas a singularinstanceof thepatternAddress . Thevirtual procedurepatternprintLabel refersto thenamefield of theenclosingPerson object.Theaddresspartof aCompany is handledin a similar way, but herethe printLabel refersto the name anddirectorfieldsof theenclosingCompany object.

Referencesto part objects

It is possibleto obtainreferencestopartobjects,asalreadymentionedin Chap-ter3.

P: ˆPerson; C: ˆCustomer; A1,A2: ˆAddress

Giventhereferencesdefinedabove, it is possibleto assigna referenceto theaddresspartof P andC to A1 andA2 asfollows:

P.adr[]->A1[]; C.adr[]->A2[]

This maybeusefulin situationswherethereis a needto handleobjectswithsimilar parts.In theaboveexample,it maybeusefulto handleobjectsthatallhaveaddressparts.Considerthefollowing declarations:

Areg: @Register(# content::< Address #);

The Areg is supposedto containa list of Address objects. In this list it ispossibleto insertany objectthathasanAddress part:

P.adr[]->Areg.insert; C.adr[]->Areg.insert

It is now possibleto scanthis registerandprint all thelabels:

Areg.scan(#do thisElm.printLabel #)

As maybeseen,theAreg objectandthecodethatusesit areindependentoftheactualobjectshaving theAddress part. Theonly commonthing for theseobjectsis thateachhasanAddress part.

Page 160: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

10.2 REFERENCEATTRIBUTES 149

Part objectsversussub-patterns

The readermay have noticedthat the possibility of treatingPerson objectsandCompany objectsasAddress objectsmaytechnicallybeobtainedby usingsub-patterns.We might have describedPerson andCompany assub-patternsof Address :

Person: Address(# name: @text;

printLabel::< (#do {print name} #);#);

Company: Address(# name,director: @text

printLabel::<(#do {print name and directory} #);#)

Eventhoughthis will technicallywork in thesameway, thereis a majordif-ferencewith respectto modeling. Whenusingpart objectswe considertheaddresspropertyto beanaspectof a personandcompany. Whenusingsub-patterns,we considerpersonsandcompaniesto beclassifiedas‘addressable’objects.Noneof theseviewscanbesaidto betheright one:it dependson theactualsituationwheretheobjectsareto beused.

Multiple part objects

It is of coursepossibleto have severalpartobjectsas,for example,shown inthestickmanexample.Thismeansthatthetechniqueusedfor having Addressobjectsaspartobjectscanbegeneralizedto having severalpartobjects,eachrepresentingdifferentaspectsof thewholeobject.

10.2 Referenceattrib utes

In theprevioussectionsa numberof examplesof usingstaticreferences/partobjectsfor modelingwhole-parthierarchieshave beengiven. In this sectionthe useof dynamicreferenceattributesfor modelingreferencecompositionwill be given. Referencecompositionis usedto describecompoundobjectswith partswhich are not ‘physically’ containedin the whole object, an ex-amplebeing the bank accountdefinedin Chapter3. A bank accounthasa Customer attribute, and it is of coursenot a good model to considertheCustomer object to be a part of the Account . Instead,a referenceto theCustomer is consideredapartof theAccount :

Account:(# Customer: ˆPerson;

Page 161: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

150 PART OBJECTSAND REFERENCEATTRIBUTES

...#)

In general,referencecompositionmaybeusedto representarbitraryrelations.The Customer attribute of an Account may be seenasrepresentinga ‘cus-tomer’ relationbetweenanaccountanda person.In this exampletherelationis oneway, in the sensethat the referenceis from theaccountto theperson,andnot vice versa. It is, of course,possibleto representtwo way relations.Considerpatternsrepresentingbooksandauthors:

book:(# theAuthor: ˆAuthor;

...#);

Author:(# theBook: ˆBook;

...#);

Therearenumerousexamplesof relationshipsof this kind. The relationshipbetweenavehicleandits owneris anotherexample,andit maybemodeledinBETA asfollows:

Vehicle: (# owner: ˆPerson; ... #)

As with the ‘customer’ relation, the ‘owner’ relation is simple in the sensethat an attributeof a Vehicle objectrefersto the ownerof the vehicle. Theabove representationof the ‘owner’ relationcannotbe usedto identify a ve-hicle ownedby a person. As before,it is possibleto introducea referenceattributeof a Person objectto referto a Vehicle :

Person: (# owns: ˆVehicle; ... #)

Theabovedescriptionassumesthatavehicleis ownedby atmostoneperson,andthata personownsat mostonevehicle. Sucha relationis calleda one-to-onerelation. A Person objectrepresentinga personthat doesnot own avehiclecouldberepresentedby lettingtheowns referencehavethevalueNONE.If we assumethata vehiclealwayshasanowner, thentheowner attributeofVehicle objectswill neverbeNONE.

In practice,agivenpersonmayown severalvehiclesandwemightwanttorepresentthis fact. In BETA this canbedoneusingrepetitionsof references,asin thefollowing example:

Person: (# owns: [...] ˆVehicle; ... #)

Page 162: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

10.2 REFERENCEATTRIBUTES 151

In practice,it maybeinconvenientto userepetitionsto representsuchrelation-ships.Insteadwe might havea Set patternfor representingsetsof referencesto objects:1

Person: (# owns: @Set(# element::<Vehicle #); ... #)

This typeof relationis calledone-to-many.The relation ‘Author writer-of Book’ is an exampleof a many-to-many

relation. An authormay write several books,anda book may have severalauthors.

Representingrelationsaspatterns

Often it is useful to representrelationshipsas instancesof patterns. Thismay be the casefor relationsthat are not binary, or if additionalattributesare neededto characterizethe relation. In the following examplea patternQuartet definesa relationcoveringphenomenasuchas‘The Beatles.’ Phe-nomenalike ‘The Mills Brothers’ and ‘Simon and Garfunkel’ may be rep-resentedasobjectsthat are instancesof patternsmodelingrelationssuchas‘Trio’ and‘Duo’:

Quartet:(# p1,p2,p3,p4: ˆPerson;

init:< (# do INNER #)#);

...theBeatles: @Quartet

(# init::<(#do JohnLennon[]->p1[]; ... #)#)

This an exampleof referencecomposition. Often more attributesthan justreferencesmay be associatedwith a relation. For a quartetits salary, list ofengagements,etc. may be represented.Considerthe ‘owner/owns’ relationfor vehicles.A Registration patternmaybeusedto representtherelation:

Vehicle: (# R: ˆRegistration ; ... #);Registration:

(# V: ˆVehicle;P: ˆPerson;RegistrationDate: @Date;...

#);Person: (# owns: @Set(# element::Registration; ... #)

1TheMjølnerBETA Systemhassucha Set patterndefinedin its basiclibrary.

Page 163: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

152 PART OBJECTSAND REFERENCEATTRIBUTES

10.3 Exercises

(1) Completethestick manexample.Usea suitablegraphicspackagefromtheMjølner BETA Systemto implementthegraphicsfor drawing astickman.

(2) Describethe many-to-many relation ‘Author writer-of Book’ whereanauthormay have written several books,and a book may have severalauthors.Discusspossiblepropertiesof therelation.

(3) Describepatternsmodelingarbitrarybinaryrelations.

10.4 Notes

For many yearsthefield of object-orientationhasbeenfocusingprimarily onclassification/specialization,and hasto someextent neglectedcomposition.This may be dueto the fact that supportfor compositionhasbeenavailablein programminganddesignlanguagesfrom theverybeginning,whereassup-port for classificationwasnew with the introductionof sub-classing(inheri-tance). Therehasthusbeena tendency to forget aboutcompositionandtryto useinheritancefor supportingcompositionalso. Compositionis just asimportantasclassificationfor organizingandstructuringknowledge.A gen-eral discussionof part objectsmay be found in (FaberandKrukow, 1990).Sub-classingversusinheritanceis discussedin (Sakkinen,1989).Theimpor-tanceof compositionhasmainly beenrecognizedwithin the databasefield,andobject-orientedanalysisanddesign,(see,for example,(Kim et al., 1987;CoadandYourdon,1990;Booch,1991)).

Theuseof relationsfor datamodelinghasbeencentralin thedatabasearea(seealsothebibliographyin Chapter18).

The stick man exampleis from (Blake andCook,1987) whereit is dis-cussedhow to supportwhole-partobjectsin Smalltalk-80,whichdoesnothavedirectsupportfor this. It is suggestedto useinstancevariablesfor supportingparts,but sinceinstancevariablesarenot visible from outsideanobject,it isnot possibleto executeanoperationcorrespondingto:

Joe.LeftLeg.theFoot.bigToe.wriggl e

They extendSmalltalkto allow methodswith nameslike:

LeftLeg.theFoot.bigToe.wriggle

TheStickMan objectmaythendefinethemeaningof thewriggle operation.If no methodwith theabove nameexists, thenan instancevariableLeftLegis assumedto exist, andthe messagetheFoot.bigToe.wriggle is sendtoleftLeg , which may have a methodtheFoot.bigToe.wriggle or it maypropagatethemessagefurther.

Page 164: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

10.4 NOTES 153

As proposedin, for example, (Raj andLevy, 1989), code reusedoesnot have to be obtained solely by meansof sub-classing(inheritance),but may also be obtained by part objects. A discussionof part ob-jects in BETA, including inheritancefrom part objects, may be found in(MadsenandMøller-Pedersen,1992). This includesacomparisonof multipleinheritanceusing multiple super-classesandmultiple inheritanceusingpartobjects. If only inheritanceof codeis a concern,then multiple inheritancefrom part objectsis almost the sameas multiple inheritancefrom multiplesuper-classes.It is similar to multiple inheritancein C++ without virtual baseclasses.Most languageswith multiple inheritanceincludea renamingschemeto handleidenticalnamesinheritedfrom differentsuper-classes.With partob-jects, the inheritedattributeswill have to be accessedusinga remotename,i.e. no nameconflictswill exist. However, somepeoplefind the useof re-motenamesto beto clumsy. (MadsenandMøller-Pedersen,1992) proposearenamingschemefor partobjects.

Additional languageconstructsfor supportingpart objectsare also pro-posedby (MadsenandMøller-Pedersen,1992).Oneof theselanguagemech-anismsis the location of a part object. Considerthe Address example,andconsiderfirst the situationwherePerson and Company are sub-patternsofAddress :

Person: Address(# name: @text;

printLabel::< (#do {print name} #);#);

Company: Address(# name,director: @text

printLabel::<(#do {print name and directory} #);#);

P: ˆPerson; C: ˆCompany; A: ˆAddress

Herethefollowing typesof assignmentsarepossible:

P[]->A[]; C[]->A[]; A[]->P[]; A[]->C[]

Thefirst two typesof assignmentsarealwayslegal, sinceA is ‘lessqualified’thanP andC. Thelattertwo assignmentsareonly legal if A refersto a Personor Company, respectively. Thisis, in general,notknownatcompile-time,andarun-timecheckisneededto testthevalidity of theassignment.Foradiscussionof this, see(Madsenet al., 1990).Considernow thesituationwhereAddressis representedasapartobject:

Person:(# name: @text;

adr: @Address(# printLabel::<(#do {print name} #);

Page 165: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

154 PART OBJECTSAND REFERENCEATTRIBUTES

#);Company:

(# name,director: @text;adr: @Address

(# printLabel::<(#do {print name and director} #);#);

P: ˆPerson; C: ˆCompany; A: ˆAddress

Theassignments:

P.adr[]->A[]; C.adr[]->A[];

correspondto the assignmentsP[]->A[]; C[]->A[] in the case wherePerson andCompany aresub-patternsof Address . In bothcases,thePersonandCompany objectsareassignedto a referencequalifiedby Address . In thesub-patterncase,the wholeobject is assigned;in the part objectcase,a partobjectis assigned.In bothcasesonly theAddress aspectsof thePerson andCompany objectsareconsidered.

In thesub-patterncaseit is possibleto assignA to P or C andconsiderthewholeobjectasa Person andCompany. This is not possiblein thepartobjectcase.(MadsenandMøller-Pedersen,1992) have suggestedthatanobjecthasa predefinedattribute loc which refersto a possiblecontainingobject. If Arefers to an Address object which is part of a Person object, then A.locrefersto the whole Person object. If A insteadis part of a Company object,thenA.loc refersto thewholeCompany object. If A refersto anobjectwhichis not part of anotherobject, then A.loc is NONE. Using loc we may nowexecuteassignments:

A.loc->P[]; A.loc->C[]

Theseassignmentscorrespondsto theassignments:

A[]->P[]; A[]->C[]

in thesensethata lessqualifiedreferenceis assignedto a morequalifiedref-erence,andbothformsof assignmentsrequirea run-timecheck.

Page 166: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 11

Pattern Variables

In this chaptera moredynamicconceptof patternsthanordinaryandvirtualpatternswill beintroduced.In thefollowing example:

T: (# A: (# ... #) {1}V: < D;

do &A;&V

#)

the evaluation&A alwayscreatesan instanceof the patternA asdescribedat{1} . The nameA is constantin the sensethat it always denotesthe samepattern.Theevaluation&V createsan instanceof somesub-patternof D. Theactualinstancecreatedis determinedby thesub-patternsof T whereV maybeextended.ThenameV maybethoughtof asavariablethatmaydenotediffer-entsub-patternsof D. V maybegivendifferentvaluesin differentsub-patternsof T and a given value for a sub-patternwill apply for all instancesof thesub-pattern.In this chapterwewill introducethenotionof apatternvariable,which maybeassigneddifferentpatternsduringaprogramexecution.

11.1 Declaration of pattern variables

A patternvariableis definedasfollows:

F: ##T

whereF is thenameof thepatternvariableandT is its qualification.F maybeassignedany patternwhich is T or sub-patternsof T.

Considerthefollowing patterns:

T1: T(# ... #)T2: T(# ... #)

155

Page 167: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

156 PATTERN VARIABLES

Then:

T1##->F##

assignsT1 asa patternto F. F maybeusedto createinstancesin evaluationsof theform:

F &F &F[]

just asfor ordinarypatterns.F maybeassignedanew pattern:

T2##->F##

or to anotherpatternvariable:

F##->F1##

whereF1 maybedeclaredasfollows:

F1: ##T

Considerthefollowing example:

(# T: (# do ’Here is ’->puttext; INNER #);T1: T(#do ’T1’->putText #);T2: T(#do ’T2’->puttext #);F1,F2: ##T;

do T1##->F1##; &F1; {1}T2##->F1##; &F1; {2}F1##->F2##; &F2; {3}

#)

In line 1, thepatternT1 is assignedto thepatternvariableF1. Thesubsequentinvocation&F1 will then generateand executean instanceof T1. The textHere is T1 will be printed. In line 2 F1 is assigneda new patternT2. Theinvocation&F1 will thengenerateandexecutean instanceof T2, andthe textHere is T2 will beprinted. Finally, in line 3 F1 is assignedto F2. SinceF1is referringto thepatternT2, the T2 patternwill alsobeassignedto F2. Theinvocation&F2 will thusgenerateandexecuteaninstanceof T2.

F is analogousto a referenceR: ˆT with respectto qualification. ThereferenceR mayreferto instancesof T or sub-patternsof T. F mayreferto thepatternT or to sub-patternsof T.

Page 168: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

11.1 DECLARATION OFPATTERN VARIABLES 157

Structure referenceof objects

For any objectit is possibleto obtaina referenceto its structure.For anobjectreferenceR, R## returnsthe structurethat wasusedto instantiatethe objectreferredto by R. Considerreferences:

R1: @T1;R2: ˆT;R3: @T2(# ... #)

Thevalueof R1## is thepatternT1, sinceR1 is an instanceof T1. Thevalueof R2## is thestructureof theobjectreferredto by R2. SinceR2 mayrefertoinstancesof T or sub-patternsof T, R2## maybeany suchpattern.Thevalueof R3## is thestructureT2(# ... #) .

Thefollowing procedurepatterncreatesanobjectwhich is an instanceofthesamepattern/object-descriptorasits enterparameter:

MakeCopy:(# S,R: ˆObject; F: ##Objectenter S[]do S##->F##; &F[]->R[]exit R[]#)

Thecopy of theS-objectwill not have thesamestateasS. All simpleobjects(integer , etc.) will have their default values(0, etc.),andall referenceswillbe NONE. Someobject-orientedlanguagesprovide a Clone operationwhichgeneratesacopy with thesamestate.Suchanoperationis currentlynotavail-ablefor BETA.

Relational operators

It is possibleto comparepatternvariableslike:

F## = T1## F## < T2## R## <= T1##

where� meansthesamepattern,) meansthattheleft-sideis asub-patternoftheright-side,and ) � meansthattheleft-sideis eitherequalto theright-sideor asub-patternof theright-side.

It is also possibleto test for equality of patternvariablesusing the if-imperative,asshown in Sections6.1and7.6.

Block structure and relational operators

Considerthefollowing declarations:

Page 169: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

158 PATTERN VARIABLES

T: (# P: (# ... #); ... #);X1,X2: @T

The two patternsX1.P andX2.P aredifferentpatterns,meaningthat the ex-pressionX1.P## = X2.P## hasthevalue false . This exampleis similar tothe Grammar examplediscussedin Section8.2, with Pascal.Symbol beingdifferentfrom Simula.Symbol .

If X1 andX2 aredeclaredasdynamicreferences:

X1,X2; ˆT1

thenthey may refer to the sameobjector to differentobjects. In the formercaseX1.P## = X2.P## will have thevaluetrue , whereasin thelattercaseitwill have thevalueFalse .

‘First class’values

Patternvariablesmake patterns‘first class’valuesin the sensethat a patterncanbe assignedto a variable,passedasa parameterto a procedurepattern,andreturnedasa resultof aprocedurepattern.

It is alsopossibleto changethe behavior at run-timeof objects. Insteadof usingvirtual procedurepatternsit is possibleto usevariableprocedurepat-terns. If variableprocedurepatternsareused,their valuecanbe completelyredefinedin sub-patterns.Consideranextensionof theexamplefrom thestartof this chapter:

T: (# A: (# ...#);V:< D;F: ##P

#)

For instancesof T andinstancesof sub-patternsof T, theattributeA is constant,V mayhave differentbindingsin sub-patternsof T. TheattributeF mayhavedifferentbindingsin differentinstancesof thesamesub-patternof T, andthebindingin agiveninstancemaybechangeddynamically:

T1: T(# ... #);X1,X2: @T1...P1##->X1.F##; P2##->X2.F##; ...; P3##->X1.F##; ...

11.2 Example

Thefollowing is anexampleof theuseof patternvariables.

Page 170: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

11.3 EXERCISES 159

Considera drawing tool for drawing boxes and ellipseson a graphicalscreenusingmenusanda mouse.Whenever the userclicks a button on themouse,one of two actionsis performed: either a symbol is drawn on thescreenor a symbolpointedat is moved. Thereis alwaysa ‘currentaction’ tobeperformed.Thecurrentactionis selectedin the ‘actionsmenu’wheretheusercanselecteither‘draw’ or ‘move.’ When‘draw’ is selected,thecurrentsymbolis drawn on thescreen.Thecurrentsymbolis selectedby theuserviathe‘symbol menu.’

The DrawingTool patternin Figure11.1 describesthe drawing tool. Ithas attributes representingthe two types of symbolsand the two types ofactions. It hasa patternvariablefor referring to the currentselectedsym-bol (CurrentSymbol ) and one for referring to the current selectedaction(CurrentAction ). TheprocedurepatternattributeSelectAction is executedwhentheuserselectsanentryin theactionmenu.SelectSymbol is executedwhen the userselectsan entry in the symbolmenu. DoAction is executedwhentheuserclicksabuttonon themouse.

When DoAction is executed, an instance of the pattern variableCurrentAction is executed. SinceCurrentAction will refer to either theDrawAction or theMoveAction , oneof thesetwo actionswill beexecuted.

WhenDrawAction is executed,aninstanceof CurrentSymbol is created.SinceCurrentSymbol will refer to either Box or Ellipse , eithera box orellipseobjectis created.

11.3 Exercises

(1) In Section7.6 the attribute jobType wasintroducedasan integer vari-able. For this to work properly, jobType must be initialized for eachjob object. Considerhow jobType insteadcouldbedefinedasa virtualpatternattributetherebyavoiding theinitialization problem.

(2) Thepatternqua maybeusedin thefollowing way:

R: ˆT;..(R[]->qua(# qual::T1 #)).x->a

Thepatternqua checksif R##<=T1## . If this is trueit returnsareferencequalifiedby T1. It is thuspossibleto usequa for testingthequalificationof apatternandsubsequentlyuseit in acomputedremotename.

Implementqua in BETA.

(3) Extendthedrawing tool from Section11.2to includeconnectorsbetweenboxesandellipses.

Page 171: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

160 PATTERN VARIABLES

DrawingTool:(# Symbol: (# ... #);

Box: Symbol(# ... #);Ellipse: Symbol(# ... #);

Action: (# ... #);DrawAction: Action

(# F : ˆSymboldo ... &CurrentSymbol[]->F[ ]; ...#);

MoveAction: Action(# ... #);

CurrentSymbol: ##Symbol;CurrentAction: ##Action;

SelectAction:(# item : @textenter itemdo (if item

// ’draw’ then DrawAction##->Curre nt Act ion ##// ’move’ then MoveAction##->Curre nt Act ion ##

if)#);

SelectSymbol:(# item: @textenter itemdo (if item

// ’box’ then Box##->CurrentSymbol ##// ’ellipse’ then Ellipse##->Current Symbol ##

if)#);DoAction:

(#do CurrentAction#)

#)

Figure 11.1 ThepatternDrawingTool .

11.4 Notes

Procedurevariablesareknown in many languages.In Lisp-basedlanguagesandfunctionalprogramminglanguagesit is usuallypossibleto passfunctions

Page 172: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

11.4 NOTES 161

aroundasargumentsof functionsandreturnfunctionsasthe resultof otherfunctions. In Algol-60 it is possibleto passa procedure/functionasanargu-mentto a procedure/function.It is not possibleto returna procedure/functionasa resultor to declareprocedurevariables.In C it is, for instance,possibleto havepointersto functions.

Most object-orientedlanguagesdo not have constructssimilar to pat-tern variables. Pattern variablesas describedherewere suggestedby OleAgesen, Svend Frølund and Michael H. Olsen in their Masters Thesis(Agesenet al., 1990).

Patternvariablesmake the principal distinctionbetweenclass-basedlan-guagessuchasBETA andclasslesslanguagessuchasSelfmoreblurred.Oneof theadvantagesof classlesslanguagesis thatsinceobjectreferencescanbepassedasparameters,etc., this givesthe power of passingclassesaroundasparameters.As hasbeenseen,patternvariablesprovide thesamepower.

In BETA it is possibleto write a ‘classless’programby meansof singularobjects.‘Instances’of thesesingularobjectsmaybecreatedasshown above.It is, however, notpossibleto definesub-classesof suchobjects.

Onemayaskthequestionwhetheror not it is usefulto have bothpatternsandobjects.Languageslike Selfdemonstratethat it is possibleto have onlyobjects.The reasonfor having bothpatternsandobjectsin BETA is that formodelingpurposesit is importantto distinguishbetweenconcepts,andphe-nomenaandtheir representationin termsof patternsandobjects.If objectsareusedfor representingconcepts,andinstancesarecreatedby meansof cloning,it may be very difficult to understandthe structureof a program. In the Ce-cil language(Chambers,1992),which is claimedto be classless,objectsaredivided into variouscategoriesincluding abstractandtemplate.An abstractobjectcanonly beusedfor inheritanceanda templateobjectcanonly beusedfor instantiation.Themotivationfor this categorizationof objectsis to avoidcertainrun-timeerrorswhenmanipulatingsuchobjects.It is very difficult toseetheprincipaldifferencebetweena templateobjectandapattern.

Page 173: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

162 PATTERN VARIABLES

Page 174: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 12

ProceduralProgramming

In this sectionweshow how to supportproceduralprogramming,i.e. viewinga programasa collectionof proceduresthat manipulatea setof datastruc-tures. The datastructuresare implementedasinstancesof classesusedlikePascalrecords. In Chapter3, variousexamplesof proceduralprogrammingweregiven. ThepatternsFactorial , Power andReciproc areall donein aproceduralstyle. Modernprocedurallanguageslike ModulaandAda includea module(calleda package in Ada) construct.In this chapterwe describetheBETA alternativesto themodule/packageconstruct.

Two interestingissuesin programminglanguagesarethenotionsof higherorder proceduresandtypes. A higherorderprocedureis a procedureparam-eterizedby proceduresand/ortypes. Similarly, a higherordertype is a typeparameterizedby proceduresand/ortypes.A procedureor typespecifiedasaparameteris calleda formal procedure or formal type. Theprocedureor typepassedasaparameteris calledtheactualprocedureor actualtype.

Therehasbeena tendency to restrictsupportfor formalproceduresin pro-cedurallanguages.Algol-60 hasfull supportof formal procedures,whereaslanguageslike PascalandAda have restrictedforms. In Ada formal proce-duresandformal typesareto a limited extentsupportedby so-calledgenericmodules.It is outsidethescopeof this bookto describegenericmodulesandotherlanguageconstructsthatsupporthigherorderproceduresandtypes. Inthischapterwepresentexamplesof virtual patternsusedasformalproceduresandtypes.

In the following, languageconstructssuchasmodule,package,genericandhigherorderprocedureandtypewill bementionedto comparehow suchconstructsmaybeexpressedwithin theobject-orientedframework presentedhere. It will beanadvantageif thereaderis familiar with suchconstructs.Itis, however, possibleto readthe following sectionswithout suchknowledge.The main purposeof this chapteris to presentvarioususeful programmingtechniques.

163

Page 175: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

164 PROCEDURAL PROGRAMMING

Complex:(# I,R: @real;

Plus:(# X,Y: @Complexenter Xdo X.I+I->Y.I; X.R+R->Y.Rexit Y#);

Mult: ...enter(I,J)exit(I,J)#);

C1,C2,C3: @Complex...C2->C1.Plus->C3

Figure 12.1 Complex class.

12.1 Functional classes

In object-orientedprogramminglanguagesthereis often an asymmetrybe-tweenoperandsof a function.ConsidertheclassComplex in Figure12.1.Thefunction+ is modeledby theattributePlus of Complex . An ordinaryexpres-sionC1 + C2 thenhastheform C2->C1.Plus . As canbeseen,theargumentsC1 andC2 aretreateddifferently.

This hasoften beencriticized. The authorsof CLU (Liskov andZilles,1974)decidedto qualify theoperationsusingclass-nameinsteadof instance-name.Theaboveoperationlookslike thefollowing in CLU:

C3:=Complex$Plus(C1,C2)

A consequenceis thatall operation-callsmustbedenotedin this way.In Smalltalk the asymmetryhasbeenkept. Numbersare viewed as in-

stancesof aclassandrespondto messages,althoughthismaynotbethemostnaturalway of modelingnumbersin a programminglanguage. Below weshow thattheprocedural/functionalstylecanbeexpressedin BETA.

Consider the definition of a complex packagein Figure 12.2. TheComplexRing classdefinesa setof attributesthat implementcomplex num-bers.TheobjectCR is aninstanceof ComplexRing . Theattributesof CRmaythenbeusedasshown in theexample.In CLU, theoperationsarequalifiedbya typename;herethey arequalifiedby anobjectname.As canbeseen,the

Page 176: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

12.1 FUNCTIONAL CLASSES 165

(#ComplexRing:

(#Complex:

(# I,R: @realenter(I,R)exit(I,R)#);

Create:(# R,I: @real; C: @Complexenter(R,I)do R->C.R; I->C.Iexit C#);

Plus:(# A,B,C: @Complexenter(A,B)do A.I+B.I->C.I; A.R+B.R->C.Rexit C#);

Mult: ...#);

CR: @ComplexRing; {package object}X,Y,Z: @CR.Complex;

do(1.1,2.2)->CR.creat e-> X;(3.1,0.2)->CR.creat e-> Y;(X,Y)->CR.plus->Z

#)

Figure12.2 Complex package.

definitionof complex numbersis ‘functional.’ Thereis noasymmetrybetweentheargumentsof theoperations.ObjectslikeCRarecalledpackageobjects.

Page 177: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

166 PROCEDURAL PROGRAMMING

T: (# T1: (# ... #);T2: (# ... #);...Tn: (# ... #);

F1: (# X: @T2; y: @T3; z: @T1enter(x,y)do ...exit z#);

F2: (# ... #);...Fm: (# ... #)

#);

aT: @T;a: @aT.T1; b: @aT.T2; c: @aT.T3;...(b,c)->aT.F1->a

Figure12.3 Definitionof asetof mutuallydependentclasses.

Mutually dependentclasses

In CLU a classdefinesa singleabstractdatatype. In Ada it is possibletodefinea packageconsistingof mutuallydependenttypes, i.e. typesthatmustknow aboutoneanother’s representation.It is straightforward to generalizethe techniqueusedfor the ComplexRing classto definemutually dependentclasses.Figure12.3illustratesasketchof classthatdescribespackageobjectswith attributesconsistingof n classesandm operations.

In Figures12.4 and12.5 an exampleof two mutually dependentclassesis shown. The patternVectorMatrixPackage definestwo classpatterns,Vector and Matrix , and a numberof associatedoperations. The Matrixoperationsmakeuseof therepresentationof a Vector object.

The notation used in the above examples has two immediate draw-backs:

� It maybeawkwardto alwayshave to qualify attributesof a packageobjectwith thenameof thepackageobject.This canbeavoidedby a mechanismsimilar to thewith-statementof Pascalor inspect-statementof Simula:

Page 178: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

12.1 FUNCTIONAL CLASSES 167

VectorMatrixPacka ge:(# Vector:

(# S: [100] @Integer;Get: (# i: enter i exit S[i]#);Put: (# e,i: @integer enter(e,i) do e->S[i] #)

#);Matrix:

(# R: [100] ˆ Vector;Init:<

(#do (for i:R.range repeat &Vector[]->R[i][] for); INNER#);Get: (# i,j: @integer enter(i,j) exit R[i].S[j] #);Put: (# e,i,j: @integer enter(e,i,j) do e->R[i].S[j] #)

#)VectorBinOp:

(# V1,V2: ˆ Vectorenter(V1[],V2[]) do &Vector[]->V3[]; INNER exit V3[]#);

AddVector: VectorBinOp(#do (for i: V1.S.range repeat V1.S[i]+V2.S[i]->V 3. S[i ] for)#);

...MatrixBinOp:

(# M1,M2,M3: ˆ Matrixenter(M1[],M2[]) do &Matrix[]->M3[]; M3.init; INNER exit M3[]#);

AddMatrix: MatrixBinOp(#do (for i: M1.R.range repeat

(for j: M1.R[i].S.range repeatM1.R[i].S[j] + M2.R[i].S[j]->M3.R[ i] .S[ j]

for)for)#);...MultMatrixByVector : ...

#);

Figure12.4 Vectorandmatrixpackage.

with aT do(# a: @T1; b: @T2; c: @T3;do (b,c)->F1->a#)

Of course,this only works if thereis just oneinstanceof theclassT. Adaalso hasa variant of the with statement. BETA doesnot have a with-statement.

Page 179: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

168 PROCEDURAL PROGRAMMING

MultMatrixByVector:(# V: ˆ Vector; M1,M2: ˆ Matrixenter(M1[],V[])do &Matrix[]->M2[];

(for i: V.S.range repeat(for j: M1.R[i].S.range repeat

V.S[i] * M1.R[i].S[j]->M2.R[i ]. S[j ]for)for)

exit M2[]#)

Figure12.5 Vectorandmatrixpackage.

� If only oneinstanceof theclassis needed,it mayalsobedesirableto avoiddeclaringtheclass.This canbeaccomplishedby definingthepackageob-ject asasingularobject:

aT: @(# T1: ...; T2: ...; ... Tn: ...;F1: ...; F2: ...; ... Fm: ...;

#)

� An alternativeto thewith statementandsingularobjectsis to useasingularinsertedobjectprefixedby T, asin

(# ...do T(# {All declarations in T are visible here} #)#)

This techniqueis oftenusedin practice.

Theexamplesin thissectioninvolvepackageobjectsthathaveonly class-andprocedureattributes.Thereis thusno stateassociatedwith thesepackageob-jects. Sincean ) object-description* maycontainvariabledeclarations,it ispossibleto describepackageobjectswith state.A singularpackageobjectlikeaT is thenquitesimilar to anAda package.A class,like T or ComplexRing ,describingpackageobjectscorrespondsto an Ada genericpackagewithoutgenericparameters.An instanceof sucha classcorrespondsto an instantia-tion of anAdagenericpackage.Laterin this chapterwe discusshow patternscanbeusedto modelgenericpackageswith genericparameters.

Page 180: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

12.2 HIGHERORDERPROCEDUREPATTERNS 169

12.2 Higher order procedurepatterns

It is possibleto definehigherorderprocedurepatternsusingvirtual procedurepatternsand/orpatternvariablesasformal procedures.By higherorder pro-cedure patternwe understanda procedurepatternthat is parameterizedby apatternor returnsa patternasavalue.

Considerthefollowing patterns:

IntFunc: (# X,Y: @integer enter X do INNER exit Y #);

PlotFunc:(# F:< IntFunc;

first,last: @Integer;Device: ˆ Image

enter(first,last,Device[])do (first,last)->forTo

(# inx: @Indexdo (inx,(inx->F))->Device.PutDot

#)#)

The patternPlotFunc is supposedto plot thevaluesof the function F in theinterval [first,last] . Assumethatwehave functions:

Square: IntFunc(#do X*X->Y #);Double: IntFunc(#do X+X->Y #)

Thefollowing ‘function calls’ will thenplot thevaluesof thesefunctions:

(15,30,somePlotter[])->PlotFunc(# F::Square #);(20,40,somePlotter[])->PlotFunc(# F::Double #);

Assumethat we want to plot the valueof the factorial function asdescribedin Chapter3. Factorial hasnot beenspecifiedasa sub-patternof IntFunc .We may‘pass’Factorial in thefollowing way:

(1,6,somePlotter[])->PlotFunc(# F::(#do X->Factorial->Y#)#)

In theaboveexample,virtual patternsareusedfor parameterizingaprocedure.The following exampleshows how this canbe doneusingpatternvariables.Thisstyleis similar to a traditionalstyleof higherorderprocedurepatterns:

PlotFunc:(# F: ##IntFunc;

first,last: @Integer;Device: ˆ Image

enter(F##,first,last,Device[])

Page 181: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

170 PROCEDURAL PROGRAMMING

do (first,last)->forTo(# inx: @Indexdo (inx,(inx->F))->Device.PutDot

#)#);...(Square##,15,30,somePlotter[])->P lotFun c;(Double##,20,40,somePlotter[])->P lotFun c;

In theabove example,a patternvariablewasusedasanenter-parameter. Thenext exampleshowsa procedurepatternthatreturnsa patternvariablevia theexit-list. The exampleshows how to definea function comp for composingtwo integerfunctions:

comp:(# f,g: ##IntFunc; h: IntFunc(#do x->f->g->y #)enter(f##,g##)exit h###);

C: ##IntFunc;...(Double##,Square##)->comp->C##;5->C->x {x=100}

12.3 Virtual classesand genericity

(Meyer, 1987a) presentsaninterestingcomparisonbetweengenericityandin-heritance,showing that,in general,inheritancecannotbesimulatedby gener-icity while genericitycan be simulatedby inheritance. However, the tech-niquesfor simulatingso-calledunconstrainedgenericitybecomeratherheavy.For this reason,unconstrainedgenericitywasincludedin Eiffel.

In thissectionweshow to whatextentvirtual classescanreplacegenericityusing the exampleof a generalclassRing (Meyer, 1988) with the attributesZero, Unity, Plus andMult . We useRing to definesub-classesComplex ,anda generalclassVector parameterizedby Ring . The Vector classis inturn usedto definea ComplexVector class.

The first versionof classRing is definedin a pure object-orientedstyle,i.e. operationslike + areasymmetrical;a+b is performedasa->b.plus . Inthe next sectionanotherversionof classRing is definedusinga functionalstyle. Herethe+ is definedasa functionof two arguments.

12.3.1 Pureobject-orienteddefinition of classRing

Thepureobject-orientedversionof classRing is shown in Figure12.6. ThegeneralclassRing definesthe virtual procedureattributes Zero, Unity,

Page 182: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

12.3 VIRTUAL CLASSESAND GENERICITY 171

Ring:(# ThisClass:< Ring;

Plus:< (# A: ˆThisClass enter A[] do INNER #);Mult:< (# A: ˆThisClass enter A[] do INNER #);Zero:< (# do INNER #);Unity:< (# do INNER #)

#);Complex: Ring

(# ThisClass::< Complex;I,R: @real;Plus::<(# do A.I->I.Plus; A.R->R.Plus #);Mult::< (# ... #);Zero::< (# do 0->I->R #);Unity::< (# ... #)

#);Vector: Ring

(# ThisClass::< Vector;ElementType:< Ring;R: [100] ˆ ElementType;Plus::<

(#do (for i: 100 repeat

A.R[i]->R[i].Plusfor)#);

Mult: ... Zero: ... Unity: ...#);

ComplexVector: Vector(# ThisClass::< ComplexVector;

ElementType::< Complex#)

C1,C2: @Complex;V1,V2: @ComplexVector...C1.Unity; C2.Zero; C1[]->C2.Plus;V1.Unity; V2.Unity; V1[]->V2.Plus;

Figure 12.6 Object-orienteddefinitionof classRing .

Plus andMult . In addition,a virtual classattribute ThisClass (explainedbelow) is included.TheclassComplex is oneexampleof asub-classof Ring .

A moreinterestingsub-classof Ring is theclassVector , whichincludesavirtual classattributeElementType qualifiedby Ring . ElementType defines

Page 183: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

172 PROCEDURAL PROGRAMMING

the classof the elementsof the vector, i.e. the elementsof the vectorhaveall the propertiesof a ring. ClassComplexVector is a sub-classof Vectorwherethe virtual classElementType is extendedto be classComplex . (Inthis examplea vectorconsistsof 100elements.By usinga virtual procedure,yielding an integervalue,it is straightforwardto parameterizethesizeof thevector.)

The virtual classThisClass is usedto ensurethat the argumentof, sayPlus , is alwaysof thesametypeasthecurrentclass.In Complex it is there-fore extendedto be a Complex , andin Vector it is extendedto Vector . Ifthe referenceA in the definition of Plus in classRing wasdefinedasA: ˆRing , thenin theextensionof Plus in Complex thereferenceA might refertoany Ring object. An explicit checkwould be neededto ensurethat A refersto a Complex object. In addition,anoperationlike V1[]->C2.Plus would bevalid. Insteadof explicitly definingavirtual classlikeThisClass , it wouldbemoreconvenientto have a predefinednamefor this. For BETA this wassug-gestedin (Kristensenetal., 1983b). In (BorningandIngalls,1981) aproposalfor Smalltalkwasmade.In Eiffel theexpressionlik e current correspondstoThisClass .

12.3.2 Functional definition of classRing

In this sectiona functionalversionof classRing is given. In languageswith apackageconceptonecandefinepackagesthatcontainthedefinitionof a typeandtheoperationsonthistype.A packageis notaclass,but ratheradefinitionof asingleobject.A genericpackage,ontheother, handresemblesaclass,butthisis verylimited. In object-orientedterminology, agenericpackagecanonlybeusedfor creatinga singleinstance(a package).It is actuallyjust templatesthatareelaboratedat compiletime; it is not possibleto addpropertieslike insub-classes.

It is possibleto modela genericpackageby a classwith virtual classandvirtual procedureattributesrepresentingthe formal typesand formal opera-tionsof thepackage.

In Figure12.7a functionaldefinitionof theclassRing is given,togetherwith a sub-classComplexRing that definesthe type complex andoperationson complex objects.Thevirtual classattributeplaystherole of thetype. Theoperationson the type aredefinedin a functional (symmetrical)way on in-stancesof classType . TheType classis extendedin sub-classesof theRingclass.To usea ComplexRing it is necessaryto createaninstanceof it (in theexample,CR is suchaninstance).All complex referencesandoperationcallsarereferredto asattributesof CR. TheRing andComplexRing classescanbecomparedto genericpackagesin Ada andCR to a genericinstantiation.Thenext examplefurtherillustratesthis.

In Figure12.8a vectoris definedusinga functionalclass.Theimportant

Page 184: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

12.3 VIRTUAL CLASSESAND GENERICITY 173

Ring:(# Type:< Object;

Plus:<(# X, Y, Z: ˆTypeenter(X[],Y[])do &Type[]->Z[];

INNERexit Z[]#);

Mult: ... Zero: ... Unity: ...#)

ComplexRing: Ring(# Type::< (# I,R: @real #);

Plus::< (#do X.I + Y.I->Z.I; X.R + Y.R->Z.R #);Mult: ... Zero: ... Unity: ...

#);CR: @ComplexRing;C1,C2,C3: ˆ CR.Type...CR.Unity->C1[]; CR.Zero->C2[];(C1[],C2[])->CR.Plus -> C3[ ]

Figure12.7 Functionaldefinitionof Ring .

thing to noticeis that theelementtypeof a vectorring is not a virtual class,instead,it is describedby the referenceactualRingElement . The reasonisthata VectorRing instancemustbeparameterizedby a specificring, i.e. aninstanceof RingElement , otherwisethe elementsof a vector include, say,complex numbersfrom differentcomplex rings,whichseemsinappropriateinthiscase.(However, it is possibleto modelthis if desired.)In theexample,thereferenceactualRingElement is givenavaluewheninit is executed.(CRistheComplexRing from Figure12.7.) This is, however, not satisfactory, sinceactualRingElement shouldnot changevalueafter the initialization, but itshoulddenotethesameComplexRing duringthelife timeof theVectorRing .This canbeaccomplishedby makingactualRingElement a ‘call-by-const’1

parameterof theclassVectorRing . It maythenbeboundwheninstantiatinga VectorRing (or oneof its sub-classes)andnot modifiedafterwards.Sincesuchparametermechanismsarewell known it will not befurtherelaborated.

1‘Call-by-const’wasusedin thefirst versionof Pascal.

Page 185: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

174 PROCEDURAL PROGRAMMING

VectorRing:Ring(# RingElement:< Ring;

actualRingElement: ˆRingElement;Type::< (# V: [100] ˆactualRingElement.T yp e #);Init:<

(# aRing: ˆRingElemententer aRing[]do aRing[]->actualRin gEl ement []#);

Plus::<(#do (for i: 100 repeat

(X.V[i][],Y.V[i][])->actualRingElement .P lus->Z.V[i]

for)#);

Mult: ... Zero: ... Unity: ...#);

ComplexVectorRing: VectorRing(# RingElement::< ComplexRing #);

CVR: @ComplexVectorRing;A,B,C: @CVR.Type...CR[]->CVR.Init

Figure12.8 Functionaldefinitionof theclassVector .

12.3.3 Classattrib utesversustype attrib utes

It could be arguedthat the definition of ComplexRing doesnot demonstratetheneedfor or usefulnessof classattributes.TheattributeType couldalsobedefinedusingapure(record)type,asin Pascal.Suchrecordobjectscould,forinstance,only beassignableandcomparable,but nothaveprocedureandclassattributesasdoclasses.

However, by usinga classattribute it is possibleto combinethe object-orientedandfunctionalstyles. The Type classof ComplexRing may have aprocedureattribute Incr that incrementsa complex numberby 1 (seeFigure12.9).It seemsmorenaturalto expresssuchanoperationin anobject-orientedstylethanin a functionalstyle.

With the additionof the Incr it is possible,in additionto functionalex-pressions,to specifyevaluationslike:

Page 186: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

12.3 VIRTUAL CLASSESAND GENERICITY 175

ComplexRing:Ring(# Type::<

(# I,R:@real;Incr: (# do I+1->I; R+1->R #)

#);...

#);

Figure12.9 Complex with local Incr operation.

VectorOfVector: Vector(# ElementType:: Vector(# ElementType:: Elm #)

Elm:< Ring;ThisClass::< VectorOfVector

#);VectorOfVectorOfComp le x: VectorOfVector

(# ThisClass::< VectorOfVectorOfCo mpl ex;Elm::< Complex

#)

Figure12.10 ClassVectorOfVector .

...; C1.Incr; ...

12.3.4 Mor eon extendingvirtual classes

In this section,theVector classof Figure12.6will befurtherelaborated.Asshown in Figure12.10,a VectorOfVector classparameterizedby Vector isdefined.A new virtual classElm hasbeenintroducedto standfor theparameterof theclassVectorOfVector . Theuseof :: insteadof ::< specifiesthatthisis thefinal extensionof ElementType , i.e. it is no longervirtual. In general,itis usefulto beableto specifythatavirtual attributecannolongerbeextended.

A noteon syntaxmayseemappropriatehere.Thesyntaxfor definingandextendingvirtualsin examplesliketheRing maybetooheavy. Instead,ausualpositionalnotationfor definitionandextensionof virtualsis beingconsidered.

Page 187: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

176 PROCEDURAL PROGRAMMING

12.4 Notes

Theexamplesin this chaptershow thateventheproceduralstyleof program-ming canbe supportedwithin a languageprimarily intendedfor the object-orientedstyleof programming.As pointedoutby others(Cox,1984;NygaardandSrgaard,1987),a programminglanguageshouldsupportmorethanonestyle. Object-orientedprogramming,proceduralprogrammingand,to a lim-ited extent, functionalprogrammingaresupportedby languageslike Simula,BETA andC++.

A propertycommonto most object-orientedprogramminglanguagesisthat everythinghasto be regardedasan objectwith methods,andthat everyactionperformedis messagepassing.The implication of this is that even atypical functionalexpressionsuchas:

6+7

getstheunnaturalinterpretation:

6.plus(7)

In Smalltalktheexpression6+7 is interpretedasthemessage+ with argument7 is sentto the object6. The resultof this messageis that the object13 isreturned.Eventhough6 and7 areobjects,thereis no reasonwhy + maynotberegardedasanobjectthataddstwo integerobjects:

plus(6,7)

Thinking object-orienteddoes not have to exclude functional expressionswhen this is more natural. Functions,typesand valuesare in fact neededto describemeasurablepropertiesof objects.

Page 188: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 13

Deterministic Alter nation

In ourcomputerizedmodelswemustbeableto representactionstakingplacein the applicationdomainbeingmodeled.Examplesof suchactionsarede-positof money in a bankaccount,reservationof a seaton a flight, pushingabutton,etc. For certainactionstheorderingin time is important,for instance,in thecasewith thesequenceof depositsandwithdrawalson a specificbankaccount.In thepreviouschapterswe have seenhow to describea sequentialorderingof actions.

Justasit is importantto be ableto describethat two actionsareorderedin time, it is importantto beableto describethat thereis no orderingin timebetweentwo actions.Thedepositof money in onebankaccountandthewith-drawal of money from anothermaytake placeindependentlyin thesensethatit is not importantto describeanorderingin time betweenthetwo actions.Inour computerizedmodelswe mustbeableto modelseveralactionsequencestakingplacein concurrency. Fromtimeto timetheactionsequencesmayhaveto besynchronized. This is, for instance,thecasewhentwo or moreagentstryto book the sameseat. A computerizedmodelmustbe ableto representthesynchronizationof actionsequences.

A numberof activitiesmaybeviewedascompoundsystemsconsistingofseveralconcurrentactionsequences.Examplesof thisaremachinesconsistingof severalparts,eachexecutinganindependentactionsequence.In othercasesanactivity maybecharacterizedby performingseveralactionsequences,butat mostoneat a time. Theactivity will thenshift betweenthevariousactionsequences.An exampleof this is acookmakingdishes.This involvesseveralongoingactivities by thecookwho constantlyshiftsbetweenthoserequiringhisattention.Anotherexampleis theagentsof atravel agency. They oftenper-form complex tasksconsistingof severalmoreor lessindependentactivities.An agentmaybe involvedin ‘tour planning,’ ‘customerservice’and‘invoic-ing.’ Theagentwill alternatebetweentheseactivities. Whenanagentshiftstoa new activity, thecurrentactivity is temporarilysuspended.Later whentheagentreturnsto this activity it is resumedat thethepoint of suspension.This

177

Page 189: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

178 DETERMINISTIC ALTERNATION

form of sequencingis calledalternation.A processorhandlingseveral devices may naturally be describedby al-

ternation. The handlingof eachdevice generatesan action sequence.Theprocessorthenalternatesbetweentheseactionsequencesdependenton whenthedevicesneedto beserved.

Alternationshouldnotbeconfusedwith trueconcurrency, whereanumberof taskstake placeat the sametime. In alternation,at mostoneof the taskstakesplaceat agiventime.

Deterministicalternationis thesituationwheretheobjectdecidesby itselfhow to alternatebetweenthedifferenttasks.Nondeterministicalternation isthesituationwhereexternaleventscausetheobjectto shift to anothertask.

In the travel agency example,eachagentservesa numberof customersandhasa file for eachcustomer. A taskfor anagentis to processa customerfile. During a working day theagentalternatesbetweenthe tasksprocessingthe customerfiles. Most of the time the agentwill decidethe order of thetasks.However, externaleventssuchastelephonecallsmayforcetheagenttochangetask.

Action sequencingappearsin several ways in programminglanguages.The simplestmechanismis sequentialexecution, whereproceduresareexe-cutedsequentiallyandthedynamicstructureof activeprocedureactivationsisorganizedasastack.

To modelconcurrency andalternation,a programexecutionmaybeorga-nizedasseveralsequentialprocesses.This modeof executionis calledmulti-sequentialexecution. Severallanguageconstructsthatsupportmultipleactionsequenceshavebeenproposed.

Oneexampleof a multi-sequentialexecutionis coroutinesequencing. Acoroutineis anobjectthathasits own stackof procedureactivations.A pro-gramexecutionwill thenconsistof anumberof coroutines.Theprocessorwillthenalternatebetweenexecutingthesecoroutines.A coroutinemaytemporar-ily suspendexecutionandanothercoroutinemay be executed.A suspendedcoroutinemaylaterberesumedat thepoint whereit wassuspended.These-quencingbetweencoroutinesis deterministicandexplicit, sincetheprogram-mer specifiesaspart of the coroutinewhen it shall suspendits actionsandwhich coroutineis to takeover.

In anumberof situationsaprogramexecutionhasto dealwith multipleac-tion sequencesthatgo on concurrently. Coroutinesarenot suitableto supportsuchconcurrentactionsequences.In the coroutinesituation,eachcoroutinehasexclusive accessto commondataandthereis no needfor synchroniza-tion. However, to handleexplicitly thesequencingbetweena largenumberofsymmetriccoroutinesrequiresstrict disciplineof theprogrammer. In thecon-currentsituation,it is oftennecessaryto beableto dealwith nondeterminism:for example,asystemwith multipleprocessors.

In BETA, actionsequencesareassociatedwith objects;objectsmayexe-

Page 190: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

DETERMINISTIC ALTERNATION 179

cutetheir actionsaspartof theexecutionof otherobjects.Suchobjectsareofkind itemandhave beencoveredin previouschapters.Objectsmayalsoex-ecutetheir actionsconcurrentlywith otherobjects,or they mayexecutetheiractionsalternatingwith otherobjects.Suchobjectsareof kind component.

Thealternationbetweentwo or moreactionsequencesmaybedetermin-istic or nondeterministic. In this chapter, deterministicalternationin BETAwill bedescribed.Concurrency is coveredin Chapter14andnondeterministicalternationin Chapter15.

In BETA, deterministicalternationis supportedbycomponentobjectsusedascoroutines.1 Coroutinesmakesit possibleto alternatebetween‘stacksofexecutions.’ Objectsare‘statemachines’in the sensethat the resultof a re-moteprocedurecall may dependon the stateof the variablesof the object.For objectsthatarecoroutines,thestatemayincludea point of execution.Ingeneral,suchanexecutionstateinvolvesa stackof procedureactivationscur-rentlycalled.Thepossibilityof saving thestateof executionmakescoroutinesusefulfor a largenumberof applications.Theseapplicationsmaybegroupedasfollows:

� With respectto the modelingof real-life phenomena,the main motivationfor coroutinesis to modelobjectsthat performalternatingactivities. Thealternationbetweencoroutinesmay be deterministicin the sensethat thesequencingis decidedby the object itself. The shifts betweencoroutinesmaybetriggeredby eventsperformedby otherconcurrentobjects,leadingto nondeterministicalternation.Onemainreasonfor introducingcoroutinesin BETA is for modelingobjectsthatalternatebetweenanumberof sequen-tial processes(tasks).

� Coroutinesmay be usedto createan illusion of concurrency. The basicschedulingof coroutinesis usuallyexplicit, sincea coroutinerelinquishingcontrolnamesthecoroutinethat is to take over. It is possibleto eliminatetheexplicit schedulingby constructionof acoroutinescheduler(anexampleof this is shown in Section13.4.2).

� A certainclassof algorithmsis bestunderstoodasa setof interlockedse-quentialexecutionstacks.This includesbacktrackingandpatternmatching.In Section13.3anexampleof suchanalgorithmis given.

� A generator is a coroutinecapableof producinga sequenceof values. Anew valueis producedfor eachinvocationof thecoroutine.Thenext valuedependson thesequenceof previouslygeneratedvalues.In Section13.2anexampleof ageneratorof factorialnumbersis given.

1In thefollowing, theterm‘coroutine’ will oftenbeusedasa synonym for objectsof thekind component.

Page 191: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

180 DETERMINISTIC ALTERNATION

R1

B

A

R1 R1

C

A

L1: L2: L3:

Figure13.1 Snapshotsof theexecutionstack.

13.1 Executionstacks

In thissectionwewill takeacloserlook atexecutionstacks,andintroducethebasicelementsof coroutines.Considerthefollowing object:

R1: @(# A: (# do ...; B; ...; C; ... #);

B: (# do ...; L2: ... #);C: (# do ...; L3: ... #);

do ...; L1: A; ...#)

The executionof R1 is organizedin termsof a stackof active objects,illus-tratedin Figure13.1. At thelabelL1 thestackonly consistsof theobjectR1,andat L2 thestackconsistsof R1, A andB. At L3, B hasterminatedandC hasbeencalled.Eachobjectonthestackhasastructuralattributecalledthereturnlink. Thereturnlink consistsof a dynamicreferenceto thecalling objectanda codepoint in thecalling objectfrom wherethecall wasmade.Thearrowsin thediagramsrepresentthesedynamicreferences.

Theorganizationof actionsequencesin termsof stacksis usefulfor mod-eling sequentialexecutions.To modelmulti-sequentialexecutions,it is nec-essaryto beableto organizea programexecutionin termsof severalstacks.Considerthefollowing object:

R2: @(# X: (# do ...; Y; ... #);

Y: (# do ...; K1: Z; ... #);Z: (# do ...; K2: ... #)

do ...; X; ... K3:#);

Page 192: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.1 EXECUTIONSTACKS 181

The executionof R2 mayalsobe illustratedby meansof a stackin thesameway asfor R1. In this chapterwe will introducelanguagemechanismsthatmake it possibleto describean object that alternatesbetweenexecutingR1andR2. First,partof R1 maybeexecuted,thenpartof R2, thenpartof R1, etc.Suchascenariois describedbelow, andillustratedin Figure13.2:

(13.2.a)The initial stateof executionconsistsof threeobjects: R1, R2 andP* . The objectP* representssomeactive object. P* is the objectthatalternatesbetweenexecutingR1 and R2. The objectsR1 and R2 arepassive. Thedynamicreferenceof theseobjectsreferto thetopelementof thestack,which initially is theobjectitself.

(13.2.b)AssumethatP* startsby executingR1. This is doneby attachingR1to thestackof P* . This figureillustratesthestateof executionwhenR1is at thelabelL1.

(13.2.c)ThisfigureillustratesthesituationwhenR1 is at thelabelL2.

(13.2.d)At this point we assumethattheexecutionof R1 is temporarilysus-pended,andthatP* startsexecutingR2 by attachingR2 to its stack.ThesituationwhenR2 is at the label K2 is shown in this figure. Note thatthe executionstackof R1 is shown with the dynamicreferenceof R1referringto thetopelementof its stack.

(13.2.e)At thispointtheexecutionof R2 maybesuspendedandtheexecutionof R1 may be resumed.This figure shows the situationwith R1 at thelabelL3.

(13.2.f) R1 maycontinueexecutionuntil it terminates.In this case,P* mayresumeexecutionof R2. ThisfigureshowsthesituationwhereR1 is ter-minatedandR2 is at thelabelK3, i.e. immediatelybeforeit terminates.

Theabovescenariomaybedescribedby thefollowing object:

(# R1: @ |(# A: (# do ...; B; C; ... #);

B: (# do ...; L2:suspend; ... #);C: (# do ...; L3: ... #);

do ...; L1: A; ...

#);R2: @ |

(# X: (# do ...; Y; ... #);Y: (# do ...; K1: Z; ... #);

Page 193: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

182 DETERMINISTIC ALTERNATION

C

R1

A

R2

P*

X

Y

Z

P*

R1 R2

P*

R2 R1

A

B

X

Y

Z

P*

P* P* P*

P*

B

R1

A

P*

P*

R1

(a) (b)

(c) (d)

(e) (f)

P*

R1

R2

R2

R2

Z

Figure 13.2 Snapshotsof alternatingexecutionstacks.

Page 194: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.1 EXECUTIONSTACKS 183

Z: (# do ...; K2: suspend;... #)do ...; X; ...; K3:#);

do M0: R1; R2; R1; R2#)

Thesymbol| describesthattheobjectsR1 andR2 maybeexecutedalternately.The imperative suspend usedwithin R1 andR2 describesthat the executionof R1/R2 is temporarilysuspended.The object containingR1 and R2 playsthe role of P* . The situationat label M0 thencorrespondsto the situationinFigure13.2.a.Thesituationscorrespondingto Figures13.2.b-eillustratetheexecutionof theabove object. In thefollowing section,the languagemecha-nismsfor coroutinesequencingaredescribedin detail.

13.1.1 Languageconstructsfor basiccoroutine sequencing

In the above example,the termsattach,suspendandresumehave beenusedfor describingthe alternationbetweenexecutionof R1 andR2. The precisemeaningof thesetermswill begivenbelow.

In addition,BETA constructsfor creatingandexecutingobjectsof thekindcomponentaredescribed.Theconstructionmodesfor thegenerationof com-ponentsarecompletelyanalogousto thosefor items. The term ‘object’ willbeusedwheneverwe describesomethingthatis truefor all threekindsof ob-jects.Whenakind, likeacomponent,is explicitly mentioned,theexplanationis only valid for thatkind of object:

Component.An objectthatcanbethebasisfor anexecutionstackis calleda component. In Section5.10.1it was said that thereare two differ-ent kinds of objects: itemsandcomponents.The objectsthat canbeelementsof the stackof a componentare usually of kind item corre-spondingto instancesof procedurepatterns.However, aswe shall seelater, they mayalsobeof kind component.

Thedeclarations

R1: @ | P;R2: @ | P (# ... #)

describethatcomponentinstancesarecreated.R1 is aninstanceof P, whereasR2 is asingularcomponent.R1andR2arestaticcomponentreferencesthatwillconstantlydenotethenewly createdcomponents.Thesecomponentsarecalledstatic componentsor part components. R1 andR2 will eachhave their ownstackof activeobjects.Initially, thestackconsistsof R1 andR2, respectively.

Thedeclaration

Page 195: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

184 DETERMINISTIC ALTERNATION

R1

R1

P*

P*

R2

R2

Rn

Rn

(a)

(b)

. . .

. . .

Figure 13.3 Generalexecutionstate.

S: ˆ | P

describesa dynamiccomponentreference. ThereferenceS maydenotecom-ponentinstancesof thepatternP. S maybeassigneda referenceto R1 by:

R1[] -> S[]

A componentinstancemaybedynamicallygeneratedby:

&|P[] -> S[]

Activestack.A programexecutionconsistsof anumberof componentstacks,asshown in Figure13.3.a.It consistsof thestackof P* , calledtheactivestack, andthestacksR1, R2 ,...,Rn, whicharesaidto besuspended. Theobjecton top of theactivestackis calledtheactiveobject; thetop-mostcomponentontheactivestackis calledtheactivecomponent. TheactiveobjectmayexecutetheactionsATTACH andSUSPEND.

Attachment.An actionATTACH(R), whereR is not a memberof the activestack,impliesthatthestackR is attachedto theactivestack.Technically

Page 196: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.1 EXECUTIONSTACKS 185

this happensby interchangingthereturnlink of P* andR. Figure13.3.billustratesthesituationafterATTACH(R1). Theexecutionof R is saidtoberesumed.

An imperative like:

R

whereR is a componentimplies that R is attachedto the active stackof thecomponentexecutingR.

ThecomponentexecutingR is saidto attach R.

Suspension.An actionSUSPEND(R), whereR is amemberof theactivestack,impliesthatthestackof R is removedfrom theactivestack.Technicallythishappensby interchangingthereturnlink of P* andR. (Notethatthisinterchangeis thesameasfor attach.Thedifferencein effect dependsonwhetheror notR is partof theactivestack.)R is saidto besuspended.

AssumethatR is thecurrentlyoperatingcomponent.Theimperative:

suspend

impliesthatR is detachedfrom theactivestack.R is now saidto besuspended.

Termination.If thecurrentlyoperatingstackfinishesexecutionof theimper-ative in its do-part,terminationof thecomponentwill take place.Thisimpliesexecutionof animplicit suspend.A subsequentattachmentwillresultin anabort event.2

Programobject. A BETA programto be executedby a BETA processoralwayshastheform:

(# ...do ...#)

that is, a BETA programis a singularobjectdescriptor. This singularobjectis actuallyof thekind component,whichmeansthatit is thebasisfor anexecutionstack.WhenaBETA programis executed,thisprogramobjectis alwaysactive. TheobjectP* usedin theabove examplesmaybethoughtof astheprogramobject.Intuitively, it maybeusefulto thinkof theprogramobjectasassociatedwith a processorof theunderlyinghardware.

2This impliesthattheprogramterminateswith a run-timeerror.

Page 197: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

186 DETERMINISTIC ALTERNATION

(# TrafficLight:(# state: @ Colordo Cycle(#

do red->state;SUSPEND;green->state;SUSPEND

#)#)North,South: @ | TrafficLight;

{Declaration of two component instances of TrafficLight}Controller: @ | {Declaration of a singular component}

(#do North; {attachment of North}

{North.state=red}South; South; {two attachments of South}

{South.state=green }Cycle(#do {wait some time}

South; North; {switch the states}#)#)

do Controller {attachment of Controller}#)

Figure 13.4 Exampleof components.

Attachmentof R implies that the componentdenotedby R will be executed.This meansthat the actionsdescribedby the imperativesin the do-partof Rareexecuted.Theexecutionof thecomponentcontinuesuntil thecomponentexecutesa suspendimperative. This will return the control to the point ofthe attachment.A subsequentexecution(attachment)of the componentwillresumethecomponentafterthesuspendimperative. Thispatternmaybecon-tinueduntil thecomponenthascompletedexecutionof its do-part.

The example in Figure 13.4 TrafficLight describescomponentsthatwhenexecutedalternatebetweentwo states,red andgreen . TheControllercomponentinitializes the stateof North to red and the stateof South togreen . It repeatedlywaits for sometime, andthenswitchesthe lights. The‘variable’state is astaticreferencedenotinganinstanceof thepatternColor .TheColor instanceis anobjectof thekind item whereasall theotherobjectsarecomponents.An item is not a coroutine. In this examplethe Color in-stanceis usedasanordinaryvariable.

Page 198: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.2 GENERATORS 187

13.2 Generators

Componentsmay have enter/exit parts. Prior to the attachmentof a compo-nent,a valuemay be assignedto the enterpart of the component.Whenacomponentsuspendsexecutionor terminates,a valuemay be assignedfromits exit part. If R is a componenthaving enter/exit parts,thenattachmentof Rwith parametertransferhastheform:

X -> R -> Y

whereX andY areevaluations.Thevalueof X is assignedto theenter-partofR, thenthe componentR is attached,i.e. executionof R is resumed.Finally,whenR suspendsexecutiontheexit partof R is assignedto Y.

In Figure13.5anexampleof acomponenthaving enter/exit partsis given.ThecomponentFactorial computesN! . A call of theform E -> Factorial-> F returnsE! in F. A subsequentcall Factorial -> F returns(E+1)! . Atany time a new enterparametermay be given. Factorial valuescomputedpreviouslyaresavedin atable,i.e.eachfactorialvalueis only computedonce.Factorial is anexampleof ageneratorthatcomputesasequenceof values.

13.3 Components and recursive procedure pat-terns

The examplesso far have shown coroutinesthat only have a fixed numberof procedureobjects(items)aspart of their actions.Suchsimplecoroutinesmaybesimulatedusingsimplevariables,sincethereis only afinite setof sus-pensionpoints. If coroutinesarecombinedwith (recursive) procedurecalls,it is muchmorecomplicatedto simulatethestateof executionat suspensionpoints. In this section,examplesof combiningcoroutinesandrecursive pro-cedurepatternswill bepresented.

Theexamplein Figure13.6showsacomponentthatgeneratesthefactorialnumbers.For eachactivationof Factorial , thenext factorialnumberis gen-erated.This is doneby meansof a recursive procedurepattern,next .3 WhenFactorial hascomputedthenext number, it suspendsits executionandexitsthe number. For eachactivation, the componentstackwill grow with a newinstanceof next . In Figure13.7,theexecutionstackof factorial is shownwhenexecutionis at thelabelL.

The examplein Figure13.8 shows the power of combiningcomponentswith executionof recursiveprocedurepatterns.It is aclassicexampleof usingcoroutines.The programdescribesa merge of two binary searchtrees. Theattribute Traverse performsan in-ordertraversalof the tree: Traverse is a

3This is not themostcleverwayof computingfactorial,but it illustratestheprinciple.

Page 199: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

188 DETERMINISTIC ALTERNATION

(# Factorial: @ | {a singular component}(# T: [100] @ Integer; N,Top: @ Integer;enter Ndo 1->Top->T[1];

Cycle(#do (if (Top<N) // True then

{Compute and save (Top+1)!...N!}(Top+1,N)->ForTo

(#do {T[inx-1]=(inx-1) !}T[inx-1]*i->T[inx ]{T[inx]=inx!}

#);N->Top

if);N+1->N;{suspend and exit T[N-1]: }

SUSPEND;{When execution is resumed after SUSPEND,}{a new value may have been assigned}{to N through enter}

#)exit T[N-1]#);

F: @ Integerdo 4->Factorial->F; {F=4!}

{This execution of Factorial will result incomputation of 1!, 2!, 3! and 4!}

Factorial->F; {F=5!}{Here 5! was computed}

3->Factorial->F; {F=3!}{No new factorials were computed by this call}

#)

Figure 13.5 A generatorfor factorialnumbers.

componentthatwill suspendandexit theelementsin thenodesvisitedduringthe traversal. The main programstartsby executingTraverse for eachofthe treesb1 andb2. Thesmallestelementof b1 will thenbedeliveredin e1,andthesmallestelementof b2 will bedeliveredin e2. The merge loop willthenprint thesmallestof thetwo elements;for example,if e1 is thesmallest,then e1 is printedandb1.Traverse will exit the next elementof b1. Thiscontinuesuntil therearenomoreelementsin thetwo trees.Figure13.9shows

Page 200: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.4 ABSTRACT SUPER-PATTERNS 189

(# Factorial: @ |(# Next:

(# n: @integerenter ndo n*F -> F;

SUSPEND;n+1-> &Next

#);F: @ Integer

do 1->F-> &Nextexit F#);

v: @Integerdo Factorial->v; { v=1 }

Factorial->v; { v=2 }Factorial->v; { v=6 }L:Factorial->v; { v=24 }

#)

Figure 13.6 Recursivegeneratorfor factorialnumbers.

Factorial Next Next Next

Figure13.7 Recursivecomponentfor computingfactorial

an exampleof two binarysearchtreesanda snapshotof the executionstate,takenimmediatelyaftertheattachof b2.Traverse . b1.Traverse is detachedat theleftmostnode(51) andb2.Traverse is resumedat thenodelabeled45.

13.4 Abstract super-patterns

A major designgoal for BETA hasbeento designa languagewith a smallnumberof basicbut generalprimitives. In addition,muchemphasishasbeenputinto thedesignof powerfulabstractionmechanisms,asin thiswayit ispos-

Page 201: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

190 DETERMINISTIC ALTERNATION

(# BinTree:(# Node: {The nodes of the binary tree}

(# elem: @ Integer;left,right: ˆ Node

#);root: ˆ Node;

Traverse: @ |(# next: @ Integer;

Scan:(# current: ˆ Nodeenter current[]do (if (Current[]=NONE) // False then

current.left[]->&Sc an;current.elem->next;SUSPEND;current.right[]->&S can

if)#);do root[]->&Scan;

MaxInt->next; Cycle(#do SUSPEND#);{Exit maxInt hereafter}

exit next#); {Traverse}

#); {BinTree}b1,b2: @ Bintree; e1,e2: @ Integer

do ...b1.Traverse->e1; b2.Traverse->e2;Merge:

Cycle(# ...do (if (e1=MaxInt) and (e2=MaxInt)//True then leave Merge if);

(if (e1<e2) // True then e1->print; b1.Traverse->e1else e2->print; b2.Traverse->e2

if)#)...

#)

Figure 13.8 Mergecomponents.

sibleto definemorespecializedconstructs.Object-orientedlanguagesprovidepowerful constructsfor definingpatternsthat describethe generalpropertiesof aclassof (partial)programexecutions.Often,suchpatternsareintendedtobeusedassuper-patternsof morespecializedpatterns,andit is not meaning-

Page 202: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.4 ABSTRACT SUPER-PATTERNS 191

76+

51, 86+

78 91,

81,

73- 96+

45. 77/

b1, b20

b1.Tra1 verse Sca1 n Sca1 n

b1.Tra1 verse Sca1 n Sca1 n Sca1 n

P2 ’ Mer3 ge

Figure13.9 Illustrationof mergecomponents.

ful to createinstancesof thesepatterns.Patternsthatshouldonly beusedassuper-patternsarecalledabstractsuper-patterns.

In this section,examplesof definingabstractsuper-patternsin BETA willbe given, includingmodelingof symmetriccoroutinesin thestyleof Simulaandtheillusion of concurrentprogramming.

13.4.1 Symmetric coroutines

Thecomponentsdescribedin theprevioussectionbehave likeso-calledsemi-coroutines. They are so called becausethereis an asymmetrybetweenthecalling coroutineandthecoroutinebeingcalled. Thecaller explicitly namesthe coroutineto be called,whereasthe calledcoroutinereturnsto the callerby executingsuspend, which doesnot namethe caller explicitly. Thereisanotherkind of coroutine,calledasymmetriccoroutine, whichexplicitly callsthecoroutineto takeover. It doesnotreturnto thecallerby meansof suspend,giving a symmetricrelationbetweenthecoroutines.In this sectionit will beshown how to modelsymmetriccoroutines.

The SymmetricCoroutineSystem pattern of Figure 13.10 is an ab-stract super-pattern that describesthe generalpropertiesof a symmetric

Page 203: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

192 DETERMINISTIC ALTERNATION

SymmetricCoroutin eSyste m:(# SymmetricCoroutine :

(# Resume:<(#do this(SymmetricCorou ti ne) []- >next [];

SUSPEND{suspend caller}#)

do INNER#)

Run: {start of initial SymmetricCoroutine}(#enter next[] {global reference declared below}do ScheduleLoop:

Cycle(# active: ˆ | SymmetricCoroutine

{currently operating component}do (if (next[]->active[] )

// NONEthen leave ScheduleLoopif);NONE->next[];active; {attach next SymmetricCoroutine}{Active terminates when it executes either}{resume, or suspend or it terminates}

#)#);next: ˆ | SymmetricCoroutine;

{Next SymmetricCoroutine to be resumed}do INNER#)

Figure 13.10 A generalsymmetriccoroutinesystem.

coroutine system. The attribute SymmetricCoroutine of Symmetric-CoroutineSystem is an abstractsuper-patterndescribingthe propertiesof asymmetriccoroutine. It mustbe usedasa super-patternfor all componentsthatareto take part in thesymmetriccoroutinescheduling.TheRun attributeis intendedfor initiating thefirst SymmetricCoroutine . Run maybeviewedasaprimitivescheduler.

A SymmetricCoroutine is activeuntil it makesanexplicit transferof con-trol to anotherSymmetricCoroutine , doneby meansof theResumeattribute.NotethatResume is avirtual pattern,whichmeansthatit is possibleto extendthedefinitionof Resume in sub-patternsof SymmetricCoroutine .

TheResumepatternmakesuseof thepseudo-referencethis(Symmetric-

Page 204: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.4 ABSTRACT SUPER-PATTERNS 193

Coroutine) , whichrefersto theenclosingSymmetricCoroutine object.As-sumethat A andB aredifferentinstancesof SymmetricCoroutine or oneofits sub-patterns.In A.Resume , this(SymmetricCoroutine) refersto A; inB.Resume , this(SymmetricCoroutine) refersto B. For any enclosingpat-ternP thereis a pseudo-variablethis(P) .

A SymmetricCoroutineSystem terminateswhentheactive Symmetric-Coroutine terminatesexecutionwithout using resume . This may happeneitherby executingasuspendor by terminatingits actionpart.

In Figure13.11,an exampleof a programusingthe patternSymmetric-CoroutineSystem is given. The problemto be solved (Grune,1977) is tocopy charactersfrom input to output.Any occurrenceof astring 4657584 mustbeconvertedto 4:9;4 , andastring 4:979<4 mustbeconvertedto 46=>4 (thelatterincludes4?584 sconvertedto 4:9;4 s). A string 4?5@9A=7575CBD979AE7575@97F;4 will thusbeconvertedinto4?5@9A=C97BA=DE7=CF;4 . TheConverter terminatesby meansof suspendwhena new-line character(nl ) is recognizedat theoutermostlevel of DoubleBtoC . Noticethat the descriptionof the Resume attribute hasbeenextendedto includeanenterparameterin DoubleBtoC .

13.4.2 Quasi-parallel systems

In this sectionit is shown how to simulateconcurrency by meansof co-routines. The exampleis inspiredby the Processmodulein (Wirth, 1982).In Figure 13.12, an abstractsuper-pattern for defining quasi-parallelse-quencing is presented. A QuasiParallelSystem defines an abstractsuper-pattern Process defining coroutines that may take part in the

quasi-parallelsequencing.A coroutinethat is to take part in the schedulingmust be a specialization(sub-pattern)of the Process pattern. Instancesofsub-patternsof Process arehereaftercalledprocesses.

The ProcessQueue patterndefinesa queueof processes.All active pro-cessesareplacedin an instanceof ProcessQueue calledActive . Eachtimea processsuspendsexecution,anew processis selectedfrom this queue.

Communicationamongprocessesis synchronizedbymeansof signals(c.f.(Wirth, 1982)). A processmaysendandwait for (someotherprocesssending)a signal.In theexampleasignalis implementedasa ProcessQueue .

In Figure13.13,theclassicproducer/consumersystemis implementedasa quasi-parallelsystem. Patternsdescribingthe behavior of producersandconsumersaredefined.Producersandconsumerscommunicateby meansofthebuffer B andthesignalsnotFull andnotEmpty . A producercomponentP1 andaconsumercomponentC1 aredeclared.

Page 205: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

194 DETERMINISTIC ALTERNATION

Converter: @ | SymmetricCoroutineS ys tem(# DoubleAtoB: @ | SymmetricCoroutine

(# ch: @ Chardo Cycle(#

do Keyboard.GetNonBla nk- >ch;(if ch // ’a’ then

Keyboard.GetNonBlan k-> ch;(if ch // ’a’ then ’b’->DoubleBtoC.Resu me

else’a’->DoubleBtoC.Re sume;ch->DoubleBtoC.Res ume

if)else ch->DoubleBtoC.Res ume

if)#)#);DoubleBtoC: @ | SymmetricCoroutine

(# ch: @ Char;Resume::< (# enter ch #);

do Cycle(#do (if ch

// ’b’ thenDoubleAtoB.Resume;(if ch // ’b’ then ’c’->Screen.put

else’b’->Screen.put;ch->Screen.put

if)// nl then SUSPENDelse ch->Screen.put

if);DoubleAtoB.Resume

#)#)do DoubleAtoB[]->Run#)

Figure 13.11 A SymmetricCoroutineSystem .

13.5 Exercises

(1) The Register pattern in Chapter6 has a ForAll patternthat scansthroughall elementsof theregister. Make a versionof Register wheretheForAll attributeis implementedasacomponent,andwhereeachcallR.ForAll returnsthenext elementof registerR.

Page 206: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.5 EXERCISES 195

QuasiParallelSystem:(# ProcessQueue:

(# Insert: {Insert a process; insert of NONEhas no effect}...;

Next:{Exit and remove some process;

If the queue is empty, then NONEis returned} ...;Remove: {Remove a specific process} ...;

#);Active: @ ProcessQueue; {The active processes}Process: {General quasi-parallel processes}

(# Wait: {Make this(Process) wait for a send to S}(# S: ˆ ProcessQueueenter S[]do this(Process)[]->S .In ser t;

this(Process)[]->A cti ve. Remov e;SUSPEND

#);Send: {Activate a process from S}

(# S : ˆ ProcessQueueenter S[]do S.Next->Active.Ins ert ;

SUSPEND#)

do INNER;this(Process)[]->A cti ve .Re move

#); {Process}Run: {The scheduler}

(# Ap: ˆ | Process {Currently active Process}do ScheduleLoop:

Cycle(#do (if (Active.Next->Ap[ ])

// NONEthen leave ScheduleLoopif);Ap[]->Active.Inser t; {Ap is still active}Ap; {Attach Ap}

#)#)do INNER#)

Figure 13.12 A generalquasi-parallelsystem.

Page 207: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

196 DETERMINISTIC ALTERNATION

ProducerConsumer: @ | QuasiParallelSyst em(# B: @ Buffer;

notFull,notEmpty: @ ProcessQueue; {Signals}Producer: Process

(# Deposit:(# E: @ BufferElemententer Edo (if B.Full // True then notFull[]->Wait if);

E->B.put;notEmpty[]->Send

#)do INNER#);

Consumer: Process(# Fetch:

(# E: @ BufferElementdo (if B.Empty // True then notEmpty[]->Wait if);

B.Get->E;notFull[]->Send

exit E#);

do INNER#);

P1: @ | Producer(# ... E1->Deposit; ... #);C1: @ | Consumer(# ... Fetch->E1; ... #);

do P1[]->Active.Inser t; C1[]->Active.Insert ;&Run

#)

Figure13.13 A producer/consumersystem.

(2) Write a programthatgeneratesfibonaccinumbers.Theprogramshoulduseacomponent(coroutine)thatworksasagenerator.

Fibonaccinumbersaredefinedasfollows:

Fib(1) = 1Fib(2) = 1Fib(n) = Fib(n-1) + Fib(n-2)

(3) Define a quasi-parallel system where the processescommunicateby meansof synchronousmessagepassingusing procedurepatternsSendMessage andReceiveMessage .

Page 208: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.6 NOTES 197

Let S andR bereferencesto processes,andlet M1andM2bereferencestomessages.ProcessS canexecute:

(R[],M1[])->SendMessage

meaningthatS wantsto sendthemessageM1to R. S cannotcontinueuntilR hasacceptedthemessage.ThishappenswhenR executes:

S[]->ReceiveMessage->M2[]

meaningthatR wantsto receive themessagefrom M2. R cannotcontinuebeforeamessageis readyfrom S.

(4) Modify theabove quasi-parallelsystemsuchthatthemessagepassingisasynchronous.This meansthata processexecutinga SendMessage cancontinueimmediately, i.e. it doesnot have to wait for the receiver toexecuteReceiveMessage .

13.6 Notes

The notion of coroutinesequencingwas proposedby (Conway, 1963). Si-mulawasoneof thefirst languagesto includecoroutinesfor supportingquasi-parallel sequencing. A majorapplicationareaof Simulais discreteeventsim-ulation.TheSimulation classof Simulaincludesabstractionsfor creatinganillusion of concurrency to beusedwhenmodelingconcurrentactions.

It is only recently that mechanismsfor supportingmultiple action se-quenceshave beenintroducedin languagessupportingobject-orientedpro-gramming. In Smalltalk it is, to a limited extent, possibleto model mul-tiple action sequencesby meansof the classesProcess, Semaphore andProcessScheduler .

In (Marlin, 1980) a distinction is made between two types of co-routine sequencing. The first, the implicit sequencingkind, only com-municatesvia first-in-first-out queues,and there is no explicit transferofcontrol betweenthe coroutines. Call-by-needparameters,lazy evalua-tion, streams(as in (ReesandClinger, 1986)) and the systemdescribedin(KahnandMacQueen,1977) areexamplesof this kind of coroutine.

For thesecondkindof coroutine,theexplicit sequencingkind, it is possibleto transfercontrolexplicitly from onecoroutineto another.

Only afew programminglanguageshavesupportfor explicit coroutinese-quencing.Simulais oneof thefew languagesthatoffersanadvanceddesign.Itintroducedthedistinctionbetweensemi-coroutinesandsymmetriccoroutines,a semi-coroutinebeingexecutedby meansof the new- or call-imperative; asubsequentdetachreturnscontrol to thecaller. Symmetriccoroutinesareal-waysexplicitly scheduledby meansof theresume-imperative.

Page 209: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

198 DETERMINISTIC ALTERNATION

Unfortunately, the details of coroutinesequencingin Simula are verycomplicated.The problemis to understandhow semi-coroutines,symmetriccoroutinesandprefixed blocksare integrated. This meansthat even experi-encedSimulaprogrammersmayhavedifficultiesin figuringoutwhatis goingon in aprogramusingcoroutines.Thedetailsof Simula’scoroutinessequenc-ing aredescribedin (Dahl et al., 1968).

A simplifiedversionof Simula’scoroutinemechanismhasbeenpresentedby (DahlandHoare,1972). A formal descriptionof part of the coroutinemechanismhasbeenpresentedby (WangandDahl,1971). This formalizationhasbeenfurtherelaboratedin (LindstromandSoffa,1981).In (Wang,1982),it wasshown thatthesemanticsof Simula’s coroutinemechanismwasincon-sistent. The problemwas that deallocationof block instancescould not beperformedasstatedby the original languagedefinition. It is arguedthat thesimplemodelof (WangandDahl,1971) cannotcopewith full Simula.Wangpresentsa detailedanalysisof Simula’s coroutinemechanism,andgivescer-tain proposalsfor changes.Theseproposalshave sinceled to a changein thesemanticsof Simula(SwedishStandard,1987).

The diagramsusedfor illustrating the BETA coroutinemechanismmaybe viewed asan informal variantof the WangandDahl model. The modelis operational,andmaybeviewedasanabstractimplementation(in fact, thecurrentimplementationin BETA follows this modelvery closely). It maybearguedthata moreabstractandlessoperationalmodelshouldbeusedfor ex-plainingthesemantics.However, from anobject-orientedperspective,wherecoroutinesareviewedasmodelsof alternatingsequentialprocessesfrom therealworld, this modelappearsquitenatural.

Explicit coroutinesequencingin theform of symmetriccoroutinesis alsopresentin Modula-2. Accordingto (Henry, 1987), thereareseveralproblemswith thedefinitionof thecoroutinemechanismin Modula-2.

For a further discussionof the history andmotivation for coroutinessee(Marlin, 1980) and(Horowitz, 1983).

Coroutinesin BETA aresimilar to semi-coroutinesin Simula.TheBETAconstructsare simplerandmoregeneralthan thoseof Simula. In addition,BETA offers thepossibilityof includingparameterswhencalling coroutines.It hasbeenshown that theBETA constructsfor semi-coroutinesmaybeusedto defineasetof attributesthatmodelSimula’ssymmetriccoroutines.

TheconstructCycle(# do Imp’ #) is similar to a prefixed block in Si-mula, whereprefixed blocksplay a major role in quasi-parallelsequencing.This is not thecasein BETA.

The Simulation classof Simula is a classicalexampleof an abstractsuper-class. It introducesthe notionsof processesand event noticesalongwith a schedulingmechanism.Simulationprogramsmay thenbe expressedasspecializationsof theSimulation class.Theterm‘abstractsuper-pattern’(super-class)originatesfrom Smalltalk.In Eiffel, abstractsuper-classis called

Page 210: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

13.6 NOTES 199

‘deferredclass.’More than20 yearsof experiencewith Simulahasdemonstratedthat the

coroutinemechanismis extremely useful, and since Simula is an object-orientedlanguage,coroutinesare certainly useful within an object-orientedframework. A major difference betweenSimula and Smalltalk is thatSmalltalk classesdo not have a do-part. It should,however, be straightfor-ward to reinvent thedo-partof Smalltalkclasses,therebyallowing Smalltalkobjectsto beactivecoroutines.

Theexperiencewith Simula’s coroutinemechanismhasbeenthestartingpoint for BETA design.As mentionedabove,thedetailsof Simula’scoroutinemechanismarevery hardto understand,andinconsistenciesin thesemanticshave recentlybeendetected.However, in mostSimulaprogramstheseprob-lemsdo not show up. Anotherproblemwith Simula’s coroutinemechanismwastheinability to transferparameterswhencalling a coroutine.Thelack ofparametersmakesit clumsyto implementgeneratorsin Simula,sinceparam-etersmustbetransferredby meansof globalvariables.

In the designof BETA, an attempthasbeenmadeto include a simpleandgeneralcoroutinemechanismthat keepsthe advantagesof Simula. Thesimplemechanism,togetherwith apowerful abstractionmechanism,makesitpossibleto implementa wide varietyof sequencingschemes.Thesymmetriccoroutinesandquasi-parallelsystemsin Section13.4.1areexamplesof this.BETA addsnothing to the basicprinciplesof coroutinesequencingusedinSimula. However, the technicaldetailsof coroutinesequencingin BETA aremuch simpler than thoseof Simula. In addition, coroutinesin BETA mayhave parameters.This makesit easierto useBETA coroutinesasgenerators.Coroutine(component)calls appearlike procedurecalls (items) wherebyahighdegreeof uniformity betweenproceduresandcoroutinesis obtained.

Thearrival of Modula-2hasresultedin arenaissancefor coroutines.How-ever, coroutinesin Modula-2areconsideredlow-level facilitiesfor implement-ing concurrentprocesses.Accordingto (Henry, 1987) thishasimpliedthatthestatusof coroutinesin Modula-2is unclear. In BETA thecoroutinemechanismis awell integratedpartof thelanguage.

Icon(Griswold et al., 1981) is anexampleof a languagethatsupportsgen-erators.

Page 211: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

200 DETERMINISTIC ALTERNATION

Page 212: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 14

Concurrency

Thesubjectof thischapteris theconcurrentexecutionof objects.In theprevi-ouschapter, we have describedhow to useobjectsof thecomponentkind fordescribingprogramsconsistingof severalexecutionstacks.It wasshown howto describeadeterministicalternationbetweencomponents.

Componentsmay also be executedconcurrently, i.e. two or more com-ponentsmay executetheir actionsat the sametime. A basicmechanismforstartingtheconcurrentexecutionof acomponentwill beintroduced.

Concurrentcomponentsmay interactin differentways: they may accessthe sameobjectsby, for example,executingprocedurepatternattributesoftheseobjects;or they may communicatedirectly by accessingattributesofeachother.

It is well known thattheconcurrentexecutionof objectsrequiresa mech-anismfor synchronizingtheaccessto sharedobjects,just asdirectcommuni-cationbetweenobjectsmayrequiresynchronization.ThebasicmechanisminBETA for synchronizationis calleda semaphore. Semaphoresare,however,only usefulfor verysimplesynchronizationproblems.Wethereforeintroducehigh-level abstractionsfor handlingmorecomplicatedsynchronizationprob-lems,includingmonitor for guaranteeingexclusive accessto anobject,andaso-calledrendezvousmechanismfor handlingdirectcommunicationbetweenobjects.1 All theconcurrency abstractionsbeingintroducedcanbedefinedbymeansof semaphores.For someof the abstractions,the completedefinitionwill begiven;for others,their semanticswill just bedefinedin English.

By meansof textualnesting(blockstructure)it is possibleto specifycom-poundsystems. A systemmayspecifyconcurrentor alternatingexecutionofoneor moreinternalobjects,andsuchacompoundsystemwill thenhavesev-eral ongoingactionsequences.Externalsystemsmay communicatedirectlywith theinternalsystemswithoutsynchronizingwith theenclosingsystem.

1TheMjølnerBETA Systemincludesa library of suchabstractions.

201

Page 213: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

202 CONCURRENCY

14.1 Concurrent executionof components

Concurrentexecutionof acomponentmaybedescribedby meansof thefork-imperative:

S.fork

whereS is a referenceto a component.The meaningof S.fork is that exe-cutionof S will take placeconcurrentlywith theexecutionof thecomponentexecutingS.fork . Executionof S will continueuntil S executesa suspendor hasfinishedexecutionof its do-part. If S suspendsits executionby meansof an explicit suspend , it maybe resumedby meansof a new S.fork . Thefork actionis in many wayssimilarto attachment,asdescribedin thepreviouschapter. Thedifferenceis thatexecutiontakesplaceconcurrently.

Thefollowing exampleincludesa bankaccountof a person(Joe)andtwocomponents,one correspondingto a bank agentdepositingmoney in Joe’saccount,andonerepresentingJoe.Joewill only bewithdrawing money fromtheaccount:

(# Account: (# ... #);JoesAccount: @Account;bankAgent: @ |

(#do cycle(#do ...; 500->JoesAccount.deposit; ... #)#);

Joe: @ |(# myPocket: @integerdo cycle

(#do ...;100->JoesAccount.Withdraw->myPocket ; ...

#)#)

do ...bankAgent.fork;{start concurrent execution of bankAgent}Joe.fork; {start concurrent execution of Joe}

#)

From time to time, the bankAgent will depositDKK 500 in JoesAccount .Joe will similarly withdraw DKK 100from hisaccount.Thefork imperativesdescribethatthebankAgent andJoe areexecutedconcurrently.

14.1.1 Simplesynchronization

The above exampleworks well as long as the bankAgent and Joe do notaccessJoesAccount at the sametime. Thereis, however, no guaranteethatthis will nothappen.Assumethat:

Page 214: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.1 CONCURRENTEXECUTIONOF COMPONENTS 203

500->JoesAccount.deposit

and:

100->JoesAccount.Withdraw->myPocke t

areexecutedat the sametime. Assumethat the balance on the accountisDKK 800beforetheactionsareexecuted.Thefollowing sequenceof actionsmaythentakeplace:

{deposit:} compute balance + amount giving the value 1300{withdraw:} compute balance - amount giving the value 700{deposit:} store 1300 in balance{withdraw:} store 700 in balance

The final effect of the two actionswill be that balance endsup having thevalue700. This is, of course,wrong, since500 hasbeendepositedand100hasbeenwithdrawn. Thefinal valueof balance shouldthushavebeen1200.

This is a standardexampleof two concurrentobjectsaccessinga sharedobjector moregenerallya shared resource. In general,it is not possibletopredictanything aboutthe orderof executionof actionsmadeby concurrentobjects. The above exampleof a possiblesequenceis just oneexampleofmany possibilities.The actualscenariodependson the underlyinghardwareusedfor implementingthe BETA processor. The valueof balance may becompletelyundefineddependingon how theunderlyinghardwarehandlessi-multaneousaccessto a memorylocation. It is thereforenecessaryto makesurethatat mostonecomponentaccessestheaccount objectata giventime.

Semaphores

To handlesynchronization,we introducethe notion of a semaphore,2 whichmaybethoughtof asakind of signalingdevicesimilar to a traffic light. If thelight is greenyoumayproceed,but if thelight is redyoumustwait. Consideranintersectionbetweentwo roads:theintersectionmaybeconsideredasharedresourceof thevehicles.To avoid two or morevehiclesin the intersectionatthe sametime, accessto thesharedresource(intersection)is controlledby atraffic light.

A semaphoreworks in the following way: it may be in two states,redandgreen.Whenanobjectwantsto accessa sharedresourcecontrolledby asemaphore,it checksits state:

G Check-in: If thestateis green,thestateis changedto red andtheobjectaccessestheresource.Whentheobjecthasfinishedaccessingtheresource,thestateis changedto green.2Webster:Semaphore: Anyapparatusfor signaling, asby lights,flags,etc.

Page 215: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

204 CONCURRENCY

G Check-out: If the stateis red, the object waits until the statebecomesgreen.Thewaiting takesplacein a queuetogetherwith otherpossibleob-jectswaiting for accessto theresource.Whenthestatebecomesgreen,thefirst objectin thequeuemayexecutecheck-in,asdescribedabove.

BETA hasa predefinedpatternrepresentinga semaphore.An instanceofsemaphore hastwo operationsP andV,3 correspondingto check-inandcheck-out, respectively. Considerthefollowing example,describingtwo concurrentcomponentsA andB:

(# S: @semaphore;A: @ | (# do imp1; S.P; imp2; S.V; imp3 #);B: @ | (# do imp4; S.P; imp5; S.V; imp6 #);

do S.V; A.fork; B.fork#)

G ThecomponentA mayexecuteimp1 andimp3 concurrentlywith any actionexecutedby B.

G Similarly, B mayexecuteimp4 andimp6 concurrentlywith any actionexe-cutedby A.

G A andB cannotconcurrentlyexecuteimp2 andimp5 . This is ensuredby thesemaphoreS. If, for instance,A hasexecutedS.P , thenB will be delayedwhenexecutingS.P andit canonly continuewhenA hasexecutedS.V . Thesemanticsof a semaphoreis that two componentscannotat thesametimeexecuteanoperationon thesamesemaphoreobject.This meansthatA andB cannotexecuteS.P at thesametime.

Thesemaphoredescribedabovehastwo states,redandgreen,andis thereforecalleda ‘binary semaphore.’ The Semaphore patternin BETA is actuallyaso-calledgeneralizedsemaphore. Suchasemaphorehasanintegervalue:

G TheP operationdecrementsthevalueandaslongasit is positive,thecallingcomponentis not blocked. Whenthe valuebecomesnegative, the callingcomponentis delayed.

G TheV operationincrementsthevalue.As longasthevalueis lessthanone,awaitingcomponentis reactivated.

G If a semaphoreis initialized to a positive valuen, thenn componentsmaycheck-inwith the semaphorebeforesubsequentcomponentsaredelayed.Initially, a semaphorehas the value zero, meaningthat it is closed. Asemaphoreis usuallyinitialized to thevalue1 usingtheV operation.3Semaphoreswere introducedby Dijkstra, who namedthe P operationafter the Dutch

word passeren, meaningto ‘pass’,andtheV operationaftervrygeven, theDutchword for ‘torelease’.

Page 216: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.1 CONCURRENTEXECUTIONOF COMPONENTS 205

Thesemaphore patternmaybedescribedasfollows:

Semaphore:(# P: (#

do (if (cnt-1->cnt)<0 // true then{delay calling component in Q} if)

#);V: (#

do (if (cnt+1->cnt)<1 // true then{reactivate a waiting component from Q} if)

#);Count:{returns no.of. processes waiting on this(Semaphore)}

(# V: @integerdo (if cnt<0 then -cnt->V if)exit V #);

cnt: @integer;Q: @Queue

#);

The stateof a semaphore is representedby an integer cnt and a queueQfor keepingtrack of delayedprocesses.Sincecnt andQ areaccessedfromboth the P andV operation,at mostoneof theseoperationsmaybeexecutedat a time, in otherwords,the executionof P andV mustbe indivisible. TheSemaphore is a pre-definedpatternof the BETA language,andis definedtohavethepropertythatexecutionof anoperationP or V is indivisible.Theabovedescriptionof Semaphore is thusnot how it is implementedin the MjølnerBETA System,sincethe above descriptiondoesnot handleindivisibility oftheP andV operations.

We may usea semaphoreto guaranteeexclusive accessto eachbankac-count,asshown in thefollowing revisedversionof theAccount pattern:

Account:(# mutex: @Semaphore; {semaphore controlling access}

balance: @integer;Deposit:

(# amount,bal: @integerenter amountdo mutex.P;

balance+amount->balance->bal;mutex.V

exit bal#);

Withdraw:

Page 217: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

206 CONCURRENCY

(# amount,bal: @integerenter amountdo mutex.P;

balance-amount->balance->balmutex.V

exit bal#);

Init:< (#do mutex.V; {Initially open} INNER #)#)

Executionof the Deposit and Withdraw operationswill no longer be ableto make simultaneousaccessto balance . It is, of course,possibleto accessbalance directly, but this is breakingtherulesof thegame.In Chapter17 itis shown how to protectattributeslike balance suchthat it is not possibletobreakthe‘rules’.

Semaphoreis a simple andprimitive mechanismfor obtainingsynchro-nization. In the above exampleit is relatively easyto be convincedthat thesynchronizationworkscorrectly. In a systemwith severalconcurrentobjectsandseveralsharedobjects,it maybedifficult to describesynchronizationbymeansof semaphores.Programsthatmake heavy useof semaphoresmaybedifficult to readandwrite. Instead,we shall introducea numberof abstractpatternsfor handlingmore complicatedforms of synchronizationandcom-munication.

14.2 Monitors

Theuseof semaphores,asin Account , is a commonway of definingobjectssharedby two or moreconcurrentcomponents.We shall thereforeintroduceanabstractionthatmakesit easierto definesuchobjects.Thefollowingpatterndescribesaso-calledmonitorpattern:

Monitor:(# mutex: @Semaphore;

Entry: (# do mutex.P; INNER; mutex.V #);Init:< (#do mutex.V; INNER #)

#)

A Monitor object hasa semaphoreattribute anda local procedurepattern,Entry , usedto define operations. The Account may be describedusingMonitor in thefollowing way:

Account: Monitor(# balance: @integer;

Deposit: Entry

Page 218: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.2 MONITORS 207

(# amount,bal: @integerenter amountdo balance+amount->balance->balexit bal#);

Withdraw: Entry(# amount,bal: @integerenter amountdo balance-amount->balance->balexit bal#);

#)

In the following, a monitor meanssomesub-patternof Monitor . An entrypattern(or entry operation ) meansa sub-patternof Entry definedwithinsomemonitor. Monitor is oneexampleof ahigh-level concurrency abstractionthatcanbedefinedby meansof semaphores.

14.2.1 Monitor conditions

It mayhappenthata componentexecutinganentryoperationof a monitor isunableto continueexecutiondueto someconditionnot beingfulfilled. Con-sider, for instance,a boundedbuffer of characters.Sucha buffer maybe im-plementedasa monitorwith two operationsPut andGet : thePut operationcannotbeexecutedif thebuffer is full, andtheGet operationcannotbeexe-cutedif the buffer is empty. A sketchof sucha buffer monitor may look asfollows:

buffer: Monitor(# R: [100] @char; in,out: @integer;

Put: Entry(# ch: @charenter chdo {wait if buffer is full};

ch->R[in]; (in mod R.range)+1 ->in;#);

Get: Entry(# ch: @chardo {wait if buffer is empty}

R[(out mod R.range)+1->out]->ch;exit ch#);

#)

Page 219: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

208 CONCURRENCY

Themeaningof a wait is that thecalling componentis delayeduntil thecon-dition becomestrue. TheMonitor patternis extendedwith anattributewaitfor this purpose:

Monitor:(# mutex: @Semaphore;

Entry: (# do mutex.P; INNER; mutex.V #);Wait:<

(# cond: @booleando ...; INNER;

(if cond//false then {wait} if)#);

Init:< (#do mutex.V; INNER #)#)

TheWait operationmustbeexecutedin thefollowing way:

wait(#do <some condition>->cond #)

where<some condition> is a booleanexpression. If a wait is executedwithin a monitorentry, thecalling componentwill bedelayeduntil thecondi-tion becomestrue. While the componentis delayed,monitor operationscanbeexecutedby othercomponents.A delayedcomponentwill beresumedpro-vided that the condition is true and that no other componentis executingamonitoroperation,i.e. exclusiveaccessto themonitoris still guaranteed.

Wemaynow givethecompleteversionof thebuffer pattern.Thecontentof thebuffer is:

R[out+1], R[out+2], ... R[in-1]

whereall theindexesaremoduloR.range . Thebuffer is full if in=out anditis emptyif in=(out+1) , againmoduloR.range .

(# buffer: @Monitor(# R: [100] @char; in,out: @integer;

full: (# exit in=out #);empty: (#exit (in = (out mod R.range)+1) #);Put: Entry

(# ch: @charenter chdo wait(#do (not full)->cond #);

ch->R[in]; (in mod R.range)+1 ->in;#);

get: Entry(# ch: @chardo wait(#do (not empty)->cond #);

Page 220: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.3 DIRECTCOMMUNICATION BETWEENCOMPONENTS 209

R[(out mod R.range)+1->out]->ch;exit ch#);

init::< (# do 1->in; R.range->out #)#);

prod: @ | (#do cycle(#do ...; ch->buffer.put; ... #)#);cons: @ | (#do cycle(#do ...; buffer.get->ch; ... #)#)

do buffer.init;prod.fork; cons.fork

#)

Monitorsandconditionsareusefulfor describingsimplecasesof sharedob-jects(by simplewe meana limited useof conditions). If the conditionsfordelayingacallingcomponentbecomecomplicated,themonitormaysimilarlybecomedifficult to programandread.

14.3 Dir ect communicationbetweencomponents

In theprevioussectionwehavedescribedamechanismfor concurrentcompo-nentsto communicatethroughsharedobjects.In many casesit appearsmorenaturalfor concurrentcomponentsto communicatedirectly insteadof usingsharedobjects.Considerthefollowing example:

(# S: @ | (# P: (# ... #) do ...; R.Q; ... #);R: @ | (# Q: (# ... #) do ...; S.P; ... #)

do S.fork; R.fork#)

Herethe concurrentcomponentsS andR call operationson eachother. Thestateof S may, however, notbemeaningfulwhenR executesP, andviceversa.In thefollowing sectionswewill introduceabstractionsfor makingit possibleto synchronizesuchcommunication.

14.3.1 Synchronizedcommunicationbetweencomponents

In this sectionwe will introducethe notionof synchronizedexecutionof ob-jects. A componentS mayrequestexecutionof anobjectattributeof a com-ponentR. ThecomponentR mustacceptthatthattherequestcanbefulfilled.

Synchronizedcommunicationis describedin an abstractpatternSystem .A System definesthenotionof a Port for controllingthecommunication.APort hasan Entry patternfor definingprocedurepatternscontrolledby theport; it alsohasanAccept operationfor signalingthatanoperationassociatedwith theport canbeexecuted.TheSystem hasthefollowing structure:

Page 221: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

210 CONCURRENCY

System:(# Port:

(# mutex,m: @semaphore;Entry: (#do m.P; INNER; mutex.V #);accept: (#do m.V; mutex.P #)

#)do ... INNER; ...#)

Thefollowing objectillustratestwo communicatingsystems:

S: @ | System(# ...do ... E1->R.M->E2 ...#);

R: @ | System(# P: @Port;

M: P.Entry(# ... enter ... do ... exit ... #);...

do ...; P.accept; ...#)

ThesystemS mayexecutea request, which is a normalremoteprocedurecall:

E1->R.M->E2

SinceM is a sub-patternof a port entry, theexecutionof Mhasto beacceptedby R beforeit is executed.

For M to be accepted,R mustexecutean accept, which hasthe followingform:

P.accept

Thecommunicationis carriedout whenS is executingR.M andR is executingP.accept . Both S andR areblockeduntil thecommunicationtakesplace.Acommunicationhastheeffect thatS andR togetherexecutetheevaluation:

E1->M->E2

This takesplaceasfollows:

(1) WhenS executesE1->R.M->E2 , aninstanceof Mis createdandE1 is trans-ferredto theenterpartof this instance(sinceE1-> is optionalthereneednot be an assignmentto the enter-part). S is now readyto executethedo-partof theM-instance.

Page 222: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.3 DIRECTCOMMUNICATION BETWEENCOMPONENTS 211

(2) WhenR executesP.accept , R hassignaledthat thedo-partof a instanceof a sub-patternof P.Entry may be executed.R will wait until suchanexecutionhastakenplace.

(3) WhenbothR andS areready, thedo-partof Mcanbeexecuted.

(4) Whenthe do-partof Mhasbeenexecuted,R will continueexecution. Inaddition,apossibleexit-part of Mis transferredto E2.

TheobjectS executingR.M is calledthesender, andtheobjectR having Masanattributeis calledthereceiver.

In the following example,two systemsProd andCons communicateviaa singleelementbuffer representedby a SingleBuf system.TheSingleBufsystemalternatesbetweenacceptinga Put anda Get :

(# SingleBuf: @ | System(# PutPort,GetPort: @Port;

bufCh: @char;Put: PutPort.entry

(# ch: @char enter ch do ch->bufCh #);Get: GetPort.entry

(# ch: @char do bufCh->ch exit ch #);do cycle(#do PutPort.accept; GetPort.accept #)#);

Prod: @ | System(#do cycle(#do ...; c->SingleBuf.put; ... #)#);

Cons: @ | System(#do cycle(#do ...; SingleBuf.get->c; ... #)#)

do Prod.fork; SingleBuf.fork; Cons.fork;#)

14.3.2 Ports controlling several operations

It is possibleto associatemorethanoneoperationwith a port, asillustratedin Figure14.1.TheMaster -systemtransmitsa sequenceof valuesto thetwoSlave -systems,andeachSlave -systemcomputesthesumof thevaluesbeingreceived.Eachvalueis receivedandaccumulatedby asynchronousexecutionof Add. A Slave objectcanbeusedaccordingto thefollowing protocol:

(1) TheClear operationmustbeusedto initiate a new sequenceof summa-tions.A Clear thusterminatesany ongoingsummation.

Page 223: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

212 CONCURRENCY

(# Slave: System(# receive: @Port;

Clear: receive.entry(# do 0->sum #);Add: receive.entry

(# V: @integer enter V do sum+V->sum #);Result: receive.entry(# S: @integer do sum->S exit S #);sum: @integer;

do 0->Sum;Cycle(# do receive.accept #);

#);Slave1: @ | Slave;Slave2: @ | Slave;Master: @ | System

(# Pos,Neg: @integer; V: [100] @integer;do {Read values to V}

Slave1.Clear; Slave2.Clear;(for inx: V.Range repeat

(if True// V[inx] > 0 then V[inx]->Slave1.Add// V[inx] < 0 then V[inx]->Slave2.Add

if)for);Slave1.Result->Po s;Slave2.Result->Ne g;

#)do Master.fork; Slave1.fork; Slave2.fork#)

Figure14.1 Exampleof concurrentsystems.

(2) TheAdd operationaccumulatesanew value.

(3) TheResult operationreturnsthecurrentsum.

In theexample,positivenumbersaretransmittedto Slave1 andnegativenum-bersaretransmittedto Slave2 .

14.3.3 Restrictedacceptance

An acceptoperationon a port signalsthat any object is allowed to executeanoperationassociatedwith theport. Sometimesit is desirableto restrictthepossibleobjectsthatareallowed to executea port operation.The restrictionmayspecifythatonespecificobjectis allowedto executea port operation,orit mayspecifythatinstancesof aspecificpatternareallowedto executeaport

Page 224: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.3 DIRECTCOMMUNICATION BETWEENCOMPONENTS 213

operation.Thesetwo typesof restrictionsaredescribedin thefollowing twosections.

Object restriction

It is possibleto restrictthesenderof anoperationby declaringtheport asaninstanceof theObjectPort pattern.TheAccept operationof anObjectPorthasan enterparameterwhich is a referenceto the object that is allowed toexecuteaportoperation.Thesyntaxfor this is:

S: ˆ | T; {some component reference}P: @ObjectPort;F: P.Entry(# do ... #);...S[]->P.accept;

The examplein Figure14.2describesan abstractpatternfor handlingreser-vationsof somekind. The reservationsare supposedto be storedin someregister. The actualway this is done is supposedto be describedin sub-patternsof ReservationHandler . At most,onepersonata time is allowedtomakereservations.An agentmakingareservationmustperformthefollowingsteps:

(1) Theregistermustbelockedby executingtheLock operation.

(2) Theagentmaythenperformoneor morereservationsusingReserve .

(3) Theagentterminatesthereservationsessionby executingClose .

Theexampleincludesasketchof ahandlerfor hotelreservations.ThesystemP describesascenarioof anagentmakingtwo hotelreservations.

Qualified restriction

The ObjectPort describedabove makesit possibleto ensurethat only onespecificsystemmayexecutea port operation.It is oftendesirableto specifythataportoperationmaybeexecutedby arestrictedsetof systems.By usingaport instantiatedfrom QualifiedPort , it is possibleto defineport operationsthatmaybeexecutedby objectsqualifiedby aspecificpattern.Thesyntaxforthis is:

T: (# ... #); {some pattern}P: @QualifiedPort;F: P.Entry(# do ... #);...T##->P.accept;

Page 225: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

214 CONCURRENCY

ReservationHandle r: System(# start: @Port;

Lock: start.entry(# S: ˆ | Systementer Sdo S[]->sender[]; false->closed; INNER#);

sender: ˆ | System;request: @ObjectPort;Reserve:< request.Entry;Close:< request.Entry(# do true->closed; INNER #);closed: @boolean

do cycle(#do start.accept;

loop: cycle(#do sender[]->request.a cce pt ;

(if closed//true then leave loop if)#)#)

#);HotelResHandler: @ | ReservationHandler

(# Reserve::<(# guestName: @text; noOfPersons,roomNo: @integerenter(GuestName,no OfPers ons )do ...exit roomNo#);

{Representation of register of hotel reservations}#);

P: @ | System(# rno1,rno2: @integerdo P[]->HotelResHandl er .Lo ck;

(’Peter Olsen’,4)->HotelRe sHandler .Re ser ve ->r no1 ;(’Anne Nielsen’,1)->HotelR esHandle r.R ese rv e-> rno 2HotelResHandler.Cl os e

#)

Figure14.2 Exampleusinga restrictedport.

Portoperationsassociatedwith P maynow beexecutedby anobjectwhich isaninstanceof T or asub-patternof T.

Page 226: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.4 COMPOUNDSYSTEMS 215

(# Producer: (# ... #);Consumer: (# ... #);SingleBuf: @ | System

(# PutPort,GetPort: @QualifiedPort;bufCh: @char;Put: PutPort.entry(# ch: @char enter ch do ch->bufCh #);Get: GetPort.entry(# ch: @char do bufCh->ch exit ch #);

do cycle(#do Producer##->PutPor t. acc ept ;

Consumer##->GetPor t. acc ept#)

#);Prod: @ | Producer

(#do cycle(#do ...; c->SingleBuf.put; ... #)#);

Cons: @ | Consumer(#do cycle(#do ...; SingleBuf.get->c; ... #)#)

do Prod.fork; SingleBuf.fork; Cons.fork#)

Figure14.3 Singlebuffer usingaqualifiedport.

The examplein Figure 14.3 illustratesthe useof a qualified port. Thesingle buffer example is modified such that Put can only be executedbyProducer objectsandGet canonly beexecutedby Consumer objects.

14.4 Compoundsystems

Compositionis a fundamentalmeansfor organizingobjects.We have severalexamplesof defining an object as compositionsof other objectsusing partobjects,referencesandblock structure.We have alsoseenhow thedo-partofanobjectmaybecomposedof otherobjects.In thissectionweshallshow howto constructcompoundsystemsthat aresystemobjectsconsistingof severalinternalmultipleactionsequences.

In BETA the actionsto be performedby a systemmay be distributedamongseveral internal systems.The internal systemsmay be more or lessindependent,andthey may accesscommondata(itemsin an enclosingsys-tem), communicatewith eachother, communicatewith external systemsor

Page 227: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

216 CONCURRENCY

control communicationbetweenexternalsystems,andthe enclosingsystem.In thefollowing, examplesof suchcompoundsystemsaredescribed.

For compoundsystemsconsistingof several internalconcurrentsystems,we areoften interestedin describingthat executionof the outermostsystemcannotterminatebeforeexecutionof all inner systemshasterminated.Theoutermostsystemmayhave to do someinitialization beforeexecutingthein-ner systems,and it may have to do somefinalization (clean-up)when theyhave finishedexecution.TheSystem patternhasanattributeconc which canbeusedfor this purpose.Conc canbeusedin thefollowing way:

S: @ | system(# S1: @ | system(# ... do ... #);

S2: @ | system(# ... do ... #);S3: @ | system(# ... do ... #);...

do ...;conc(#do S1.start; S2.start; S3.start #);...

#)

WhenS is executed,it will eventuallyexecutetheconc object,wherethedo-part describesthat concurrentexecutionof S1, S2 and S3 is initiated. Thedo-partof conc will thenwait for terminationof S1, S2 andS3. Whentheyhave terminated,executioncontinuesafterconc .

14.4.1 Indir ect communicationbetweeninternal systems

The internalsystemsof a compoundsystemmaycommunicateindirectly viaglobalobjectsin theenclosingsystem.Suchsharedobjectsshouldbedefinedasmonitorobjects.

The example in Figure 14.4 describesa histogram,representedby theHistogram system, which is an example of a compoundsystem. TheHistogram systemconsistsof two internalsystemsanda monitor, the mon-itor representingthe datain the histogram. The Display systemconstantlydisplaysthehistogramon a screen.Thehistogrammaybechangedby meansof external requests.The Update systemhandlespossibleexternal requestsandupdatesthehistogramdata.

The Display andUpdate systemsneednot synchronizeasthe Displaysystem always displays the latest version of the histogram. SincehistogramData is representedasa monitor, theoperationson thehistogramdataareindivisible.

The Display systemreadsthe histogramby requestingexecutionof theglobal item Get . Similarly, theUpdate systemupdatesthehistogramdatabyexecutionof Add andSub. NotethatnewValue is anattributeof Histogram ,

Page 228: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.4 COMPOUNDSYSTEMS 217

(# Histogram: @ | system(# histogramData: @monitor

{representation of the histogram}(# R: [100] @integer;

Add: entry (# i: @integer enter i do R[i]+1->R[i] #);Sub: entry

(# i: @integer enter i do (R[i]-1,0)->Min-> R[i ] #);Get: entry(# i,V: @integer enter i do R[i]->V exit V #)

#);Display: @ | system

(# i: @integerdo cycle(#

do (i+1) mod 100->i;(i,i->histogramDat a. Get )-> Scr een.s how

#)#);Update: @ | system(#do cycle(#do request.accept #) #);request: @Port;newValue: request.entry

(# V: @integerenter Vdo (if V>0 then V->histogramData.A dd

else -V->histogramData .Su bif)

#)do conc(#do Display.start; Update.start #)#);

S: | system(#do cycle(#do ...; someValue->Histogra m.newVal ue #)do conc(#do Histogram.start; S.start #)#)

Figure14.4 Exampleof compoundsystem.

but controlled by the internal Update system. S is some systemusingHistogram , andit communicateswith the Histogram systemindependentlyof its internalconcurrentbehavior.

14.4.2 Communication with internal systems

Fromoutsidea systemit is possibleto communicatedirectly with its internalsystemswithout synchronizingwith the enclosingsystem.The Pipe systemin Figure14.5consistsof threeinternalconcurrentsystems,DisAsm , SquashandAsm. A Pipe objectreceivesa sequenceof text lines, transformingsub-

Page 229: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

218 CONCURRENCY

strings** into ˆ . Thenthe input lines areformattedinto lines consistingof80 characters.A blankis insertedbetweentheoriginal input lines.This job isdividedbetweentheinternalsystems:

G The DisAsm systemreceivesan input line andtransmitseachcharacterintheline to theSquash system.NotethattheDisAsm systemcontrolsaPortin anenclosingsystemobject.

G TheSquash systemreplacessubstrings** by ˆ andtransmitstheoutputtoAsm.

G TheAsmsystemformatsthecharactersequenceinto linesconsistingof 80characters.

The Prod systemtransmitsinput lines to the Pipe , andthe Cons systemre-ceiveslinesfrom thePipe . Fromtheseclientstheinternalconcurrentbehaviordoesnotaffect theuseof thePipe .

14.5 Readersand writers problem

A classicalsynchronizationproblemis theso-calledreadersandwritersprob-lem,which maybeformulatedin thefollowing way: anobjectis sharedby anumberof concurrentcomponents.Thecomponentsmaybedividedinto twoclasses,dependingonhow they usethesharedobject:

Readers:A readercomponentwill only observe thestateof theobject.Sev-eralreadersmayaccesstheobjectat thesametime.

Writers: A writer componentwill modify the stateof the object. A writermusthaveexclusiveaccessto theobject.

As an exampleof a sharedobject,considera document.Several readersareallowedto extractpartsof thedocumentor print it. Severalwritersareallowedto modify the documentby insertingnew text or by deletingtext. However,eachsuchoperationmustbeindivisible. Thefollowing patterndefinesa doc-umentin theform of amonitor. TheoperationsInsert andDelete areusualentryoperations,i.e. they haveexclusiveaccessto themonitor. TheoperationsGetSub andPrint aredefinedassub-patternsof readerEntry , which is de-fined in monitor . ReaderEntry is a control patternfor definingoperationsthat canbe executedat the sametime. A readerEntry cannot,however, beexecutedat thesametime asanentryoperation:

Document: monitor(# doc: @text

Insert: entry(# i,j: @integer; T: @text

Page 230: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.5 READERSAND WRITERSPROBLEM 219

(# Prod: @ | System(#do cycle(#do getLine->Pipe.Put #)#);Pipe: @ | System

(# In: @Port;Put: In.Entry(# L: @text enter L do L->inLine #);inLine: @text;DisAsm: @ | System

(#do cycle(#

do In.accept;inLine.scan(#do ch->Squash.put #);’ ’->Squash.put

#)#);Squash: @ | System

(# P: @Port; ch: @char;Put: P.Entry(# c: @char enter c do c->ch #);

do cycle(#do P.accept;

(if ch // ’*’ thenP.accept;(if ch // ’*’ then ’ˆ’->Asm.put

else ’*’->asm.put; ch->asm.put if)else ch->Asm.put

if)#)#);Asm: @ | System

(# P: @Port; ch: @charPut: P.entry(# c: @char enter c do c->ch #);

do cycle(#do OutLine.clear;

(for i: 80 repeat P.accept; ch->OutLine.put for);Out.accept

#)#);Out: @port;Get: Out.Entry(# L: @text do OutLine->L exit L #)OutLine: @text

do conc(#do DisAsm.start; Squash.start; Asm.start #)#);

Cons: @ | System(#do cycle(#do Pipe.Get->putLine #)#)do conc(#do Prod.start; Pipe.start; Cons.start #)#)

Figure14.5 Compoundsystemwith internalcommunicatingsystems.

Page 231: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

220 CONCURRENCY

enter(i,j,T)do {insert T between pos. i and j in doc}#);

Delete: entry(# i,j: @integerenter(i,j)do {delete characters from pos. i to j in doc}#);

GetSub: readerEntry(# i,j: @integer; T: @textenter(i,j)do {get from doc substring i-j to T}exit T#);

Print: readerEntry(# P: ˆ printerenter P[]do {send document to printer P}#)

#)

ThereaderEntry maybedefinedasfollows:

Monitor:(# mutex,countMutex: @Semaphore;

rCount: @integer;entry: (# do mutex.P; INNER; mutex.V #);readerEntry:

(#do countMutex.P;

(if rCount+1->rCount // 1 then mutex.P if);countMutex.V;INNER;countMutex.P;(if rCount-1->rCount // 0 then mutex.V if);countMutex.V

#);...

#)

ThevariablerCount keepstrackof thenumberof concurrentreadoperationstaking placeat the sametime. When the first readoperationis started,themonitoris enteredby executingmutex.P . Subsequentreadoperationscannowenterwithout beingblockedby mutex . An attemptto entervia entry cannottake placeaslong asa readeris executing. Whenthe last readerleavesthe

Page 232: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.6 EXERCISES 221

monitor, it is openedby executionof mutex.V . The semaphorecountMutexis usedfor guaranteeingexclusiveaccessto rCount .

The above definition of the monitor hasthe propertythat no readerwillwait unlessthesharedobjectis accessedby awriter, meaningthatareaderwillnothaveto wait justbecauseawriter is waiting for otherreadersto releasetheobject.An alternativewouldbeto definethemonitor in suchawaythatwhenawriter wantsaccess,it will getit asfastaspossible,i.e. possiblenew readerswill have to wait. This is left asanexercise.

14.6 Exercises

(1) Considerthemaster/slaveexample.A Slave objectcomputesa summa-tion of thevaluesreceived. Definea Slave patternthataccumulatesthecomputationof a binary function F. This shouldbe doneby defininganabstractpatternSlave that is parameterizedwith a function F, andanull elementnull . If theSlave receivesthevaluesv1,v2, ..., vn , itshouldcompute:

null->ac; (ac,v1)->F->ac; (ac,v2)->F->ac; ...;(ac,vn)->F->ac

(2) Make a completedefinitionof thewait attributeof theMonitor patternusingsemaphores.

(3) Makeacompletedefinitionof thepatternsPort , Entry andaccept usingsemaphores.

(4) Considerthehistogramexamplein Figure14.4.Whatconsequencesmayit have to definetheGet attributein thefollowing way?

Get: Entry(# i: @integer enter i exit R[i] #)

Discussthe problemsof referringto objectsin an enclosingmonitor orsystemfrom theenteror exit partsof anentryoperation.

(5) Definea monitorpatternthathandlesthereadersandwritersprobleminsucha way that a writer will get accessto the sharedobjectasquicklyaspossible. Possiblenew readersshouldthenwait until the writer hasfinished.

(6) Describein BETA a machinethat canmake coffee andsoup. The ma-chinehasthefollowing characteristics:

1. ThecustomercanpusheithermakeCoffee or makeSoup.

2. If makeCoffee hasbeenpushed,he/shecan take out the coffee.Similarly, if makeSoup hasbeenpushed.

Page 233: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

222 CONCURRENCY

3. makeCoffee andmakeSoup cannotbe pushedagainuntil the cof-fee/souphasbeentakenout.

Next, extend the machineto be able to make tea also. The extendedmachineshouldbedescribedasa sub-patternof thecoffeeandsoupma-chine.

(7) Considera systemwith nestedinternal concurrentsystems,wheretheinternalsystemsmanipulatetheportsin theenclosingsystem:

S: @ | system(# p1: @port; p2: @port; p3:@port;

m1: p1.entry(# ... #); ...m2: p2.entry(# ... #); ...m3: p3.entry(# ... #); ...

S1: | system(# ... do ... p1.accept; ... #);S2: | system

(# ... do ... p2.accept; ...; p3.accept; ... #)do conc(#do S1.start; S2.start #)#)

Discusswhich operationsa sendercan apply to S dependingon theaccept operationsexecutedby the inner systems.Will the operationsthatcanbeappliedto S bemutuallydisjoint or concurrent?Discusstheadvantagesanddisadvantagesof this.

(8) Thesystem /port patternsdescribedin thischapterarestaticin thesensethat a system canonly openoneport at a given time unlessthereareinternalsystem s.

Designand implementa new system /port wherea system can openmorethanoneport at thesametime.

Comparethis style of communicationwith thatusingnestedconcurrentsystemsfrom thepreviousexercise.

(9) ConsiderasystemA thatcanbein oneof threestates,state1 , state2 orstate3 . In eachstateoneor moreportsmaybeopen.Whencommunica-tion takesplace,A changesto anew statedependingon someconditions.If cond1 is true,thenext stateis state1 , if cond2 is true,thenext stateis state2 , andif cond3 is true, thenext stateis state3 . DescribeA inBETA.

Considera systemB, which is like A exceptthatstate1 consistsof twosubstatesstate11 andstate12 . SystemB changesto state11 if cond1and cond11 is trueandto statestate12 if cond1 and cond12 is true.DescribeB in BETA asasub-patternof A.

Page 234: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

14.7 NOTES 223

14.7 Notes

It is outside the scope of this book to give a complete bibliog-raphy of concurrent programming. Important contributions to thiswork have been made by Dijkstra (Dijkstra,1968), Concurrent Pas-cal (Brinch-Hansen,1975) (and other work by Brinch-Hansen), CSP(Hoare,1978), andAda (USDepartmentof Defense,1980).

The semaphoreconceptwas introducedby Dijkstra in (Dijkstra,1968).The monitor conceptswere introduced in (Hoare, 1978; Brinch-Hansen,1975). TheBETA conc patternis similar to Dijkstra’s parbegin, parend,buttheconstituentpartsof aconc objectaresystems(asin CSP)andnotarbitraryimperatives.

Synchronizationbetweensystemobjectsis similar to the handshake inCSPor rendezvous in Ada. In CSP, both the senderpart and the receiverpart in a communicationmustbenamed.In Ada, only thesendermustnamethe receiver, whereasthe receiver acceptsall systems.The BETA approachincludesthesetwo extremesasspecialcases.

Few programminglanguagessupport compoundsystemsin a generalsense. In Ada, for example, it is possibleto specify compoundsystemsinthe form of nestedtasks.However, thecommunicationwith internaltasksislimited. It is not possiblein Ada to call entryproceduresof internaltasksof atask.

The ideaof usingsemaphoresandabstractclassesandproceduresto de-fine higherlevel concurrency abstractionswasfirst proposedby JeanVaucherin (Vaucher, 1975), whereit wasshown how to defineamonitorabstraction.

Most concurrentprogramminglanguageshave built-in mechanismsforconcurrency, communicationand synchronization. The actualmechanismsdiffer from languageto language.Monitorsandrendezvousaretypicalexam-ples. BETA hascurrentlyno built-in mechanismsexceptfor semaphoreandfork, becauseit is possibleto defineabstractpatternsfor many of the com-monlyusedhigh-levelconstructs.Experiencewith thisstrategy may, however,imply thatsomebuilt-in mechanismsshouldbeintroduced.

Page 235: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

224 CONCURRENCY

Page 236: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 15

Nondeterministic Alter nation

In Chapter13 the notion of alternationwasintroduced.Alternationis a se-quencingform usedto describea systemthat executesseveralactivities, butat mostoneat a time. As mentionedin the introductionto Chapter13, alter-nation is a usefulmechanismfor modelingagentsthat alternatesbetweenanumberof moreor lessindependentactivities. Alternationmayalsobeusedto structureaprogramusingcomponentswithoutexplicitly having to synchro-nizeaccessto commonobjects.This is in contrastto concurrency, which is asequencingform usedfor describinga systemthatexecutesseveralactivitiesat the sametime. In the concurrentsituation,accessto sharedobjectsmayhave to besynchronized.

Alternatingexecutionof componentsmay be usedto handlethe nonde-terminismof communicationin a systemof concurrentcomponents.A com-ponentinvolvedin communicationswith morethanonecomponentmaythenwait for oneor moreactsof communicationat thesametime.

In many situationsthe differentactsof communicationaremoreor lessindependent.AssumethatthesystemA communicateswith systemsB, C, DandE. Thenit maybethattheactsof communicationwith B andC areperformedin onesequenceandthe actsof communicationwith D andE areperformedin anothersequence,but thereis no sequencingbetweenthe two groupsofcommunication. In sucha situationit may be morenaturalto describethecommunicationsequencesby meansof alternatingcomponents.In theaboveexample,systemA canbedescribedasa compoundsystemconsistingof twoalternatingcomponents,onefor communicationwith B andC andanotherforcommunicationwith D andE. In thenext sectionweshow how to describethissituationin BETA.

In Chapter13, deterministicalternation(coroutinesequencing)hasbeendescribed. In this chapterthe nondeterministicform of alternationwill bepresented.Nondeterministicalternationis only meaningfultogetherwith con-currency. A systemobjectexecutingconcurrentlywith othersystemsmaybeinvolvedin anumberof ongoingdialogswith someof theothersystems.Such

225

Page 237: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

226 NONDETERMINISTICALTERNATION

a systemwill typically startan internalcomponent(coroutine)for eachsuchongoingdialog. Thesecomponentswill thenbeexecutedalternately, andtheschedulingwill benondeterministicdependingonwhentheothersystemsarereadyto communicate.

The mechanismfor specifying alternationis not a primitive languagemechanism,but is definedasanattributeof theSystem pattern.

15.1 Alter nating executionof components

Thefollowing exampleshows a BETA programcontainingthreecomponentsC1, C2 andC3:

System(# C1: @ | System(# ... SUSPEND... #);

C2: @ | System(# ... SUSPEND... #);C3: @ | System(# ... SUSPEND... #)

do alt(# do C1.start; C2.start; C3.start #)#)

C1, C2 andC3 areobjectsof the componentkind. Componentsmay be exe-cutedalternatelyasspecifiedby theimperative:

alt(#do C1.start; C2.start; C3.start #)

Thealt patternis anattributeof System . Alternatingexecutionmeansthatatmostoneof thecomponentsis executingits actionpartata time. Thecompo-nentsnot executingactionsaredelayedat well definedpointsin their actionsequence.Thesepointsarethe sameat which interleaving (i.e. shift of exe-cutionto anothercomponent)maytakeplace.Interleaving maytakeplace(1)at thebeginningof theaction-partof thecomponent,(2) whenthecomponentis attemptingto communicate(seebelow), and(3) whenthe componenthassuspendedits action-sequence.

As mentioned,interleaving may, for instance,take placewhenthe activecomponentsattemptto communicatewith anothercomponent.Communicateheremeansthat the componentattemptsto executeeitheranentry operationor anaccept.

Thesituationmentionedat thebeginningof this chapterwith a systemAperformingonecommunicationsequencewith B andC andanothersequencewith D andE maytakeplaceasfollows:

(1) The sequenceinvolving B andC may, for example,be asfollows: (a) Battemptsto executeanentryoperationA.putB , whichwill have to matchacorrespondingoperationPB.accept executedby A; (b) A will thenexe-cutesomeactionsI1 ; (c) A will thenattemptto executeanentryoperationC.putC ; (d) A will thenexecutesomeactionsI2 ; (e) This sequencemayberepeated.

Page 238: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

15.1 ALTERNATING EXECUTIONOF COMPONENTS 227

(# A: @ | system(# PB: @port; putB: PB.entry(#...#);

X1: @ | system(#do cycle(#do PB.accept; I1; C.putC; I2#);

PD: @port; putD: PD.entry(#...#);X2: @ | system

(#do cycle(#do PD.accept; J1; E.putE; J2#)

do alt(#do X1.start; X2.start #)#);

B: @ | system(#do ...; A.putB; ... #);C: @ | system

(# PC: @port; putC: PC.entry(#...#)do ...; PC.accept; ...#);

D: @ | system(#do ...; A.putD; ... #);E: @ | system

(# PE: @port; putD: PE.entry(#...#)do ...; PE.accept; ...#);

do conc(#do A.start; B.start; C.start; D.start; E.start #)#)

Figure15.1 A skecthof analternatingsystemA.

(2) A similar sequencemaybeperformedinvolving D andE.

Thisscenariois describedin Figure15.1.NotethatA hastwo internalcompo-nents,X1 andX2, eachexecutingoneof thesequencesmentionedabove. Thealt control-patternperformsanalternatingexecutionof X1 andX2, in whichcaseat mostoneof X1 andX2 is executingat thesametime.

ExecutionmayalternatebetweenX1 andX2 at thecommunicationpointsPB.accept; , C.getC , PD.accept andE.putE . For example,if X1 is execut-ing andit attemptsto executePB.accept , but B is notreadyto executeA.putB ,thenX1 maybetemporarilysuspendedandX2 mayberesumed.

At somepoint,bothX1 andX2 maybedelayedwhile waitingfor communi-cationto take place:X1 maybewaitingat PB.accept andX2 maybewaitingat E.putE . TheX1 systemmayresumewhenB is readyto communicate,andX2 mayresumewhenE is readyto communicate.In this situation,A maybe

Page 239: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

228 NONDETERMINISTICALTERNATION

seenaswaiting for a communicationwith eitherB or C, andit communicateswith thefirst onewhich is ready.

ThesystemA maybecharacterizedasexecutingthefollowing interleavedsequencesof imperatives:

S1: PB.accept; I1; C.putC; I2; PB.accept; I1; C.getC; I2; ...

S2: PD.accept; J1; E.putE; J2; PD.accept; J1; E.putE; J2; ...

TheS1sequenceis generatedby X1 andtheS2sequenceis generatedby X2.The two sequencesareinterleaved at the communicationpointsPB.accept ,C.putC , PD.accept andE.putE . Thefollowing sequenceis oneexampleof apossibleinterleaving of S1andS2

PB.accept; I1; PD.accept; J1; E.putE; J2; C.putC; I2;PD.accept; J1; PB.accept; I1; C.putC; I2; E.putE; J2; ...

15.2 A distrib uted calendar

Considera distributedcalendarsystem. Eachpersonin an organizationhasa calendarobjectwhich keepstrack of dayswherethe personis engagedinmeetings.For simplicity, ameetingis alwaysoneday.

A personwhowantsto arrangeameetingfor agroupof peoplecanattemptto reserveameetingdatefor thisgroup.Thecalendarsystemthenchecksif therequesteddateis free,andcheckswith thecalendarsof thosepeopleinvolvedif thedaterequestedis free. If thedateis freefor all thoseinvolved,thedatewill bereserved.

While a calendarsystemis checkingwith the peopleinvolved in the re-questedmeeting,it mustbe ableto answerrequestsfor meetingsfrom othercalendarsystems.

In Figures15.2and15.3a Calendar patternis described.For simplicity,only Calendar objectsareassumed,i.e. no objectsrepresentingpersonsareincluded. This meansthat insteadof reservinga meetingdatefor a groupofpeople,ameetingis reservedfor agroupof Calendar objects.

TheownerHandler takescareof an initial reservation from theownerofthe calendar. The start -port representsa statewherethe ownerHandler isreadyto acceptthe reserve operationfor reservinga meeting.Theend -portrepresentsa statewherethe ownerHandler is readyto acceptthe confirmoperation,which informs the owner aboutwhetheror not the meetingcouldbereserved.

When a reserve -operationhas been executed, the procedurepatterncheckDate checkswhetherit is possibleto reserve a meetingfor that day.First, the day mustbe free for the owner of the calendar. If this is the case,thentheday is checkedwith all membersof thegroup. Eachgroupmember

Page 240: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

15.2 A DISTRIBUTED CALENDAR 229

Calendar: system(# days: [365] @integer; {representation of the calendar dates}

ownerHandler: @ | system(# day: @integer; {date for initiated meeting}

group: ˆCalendars; {involved Calendars}start: @port;reserve: @start.entry

(# D: @day; G: ˆCalendarsenter(D,G[]) do D->day; G[]->Group[]#);

Ok: @boolean;checkGroup:

(#do (if days[day]//free then

tmpBooked->days[d ay] ; true->Ok;group.scan(#do (day->theCalendar .ot her sHand ler .re se rve )

and Ok->Ok#);group.scan(#do Ok->theCalendar.o the rsH andle r.c onf ir m#)(if Ok//true then booked->days[day]

else free->days[day]if)if)#);

end: @port;confirm: end.entry

(# ok: @boolean do Ok->ok exit ok #);do cycle(#do start.accept; checkGroup; end.accept#)#);

othersHandler: @ I system (# ... #)do alt(#do ownerHandler.start ; othersHandler.sta rt #)#)

Figure15.2 A distributedcalendar.

is temporarilyasked to reserve the day, returningtrue or falsedependingonwhetheror not they can.Finally, all membersof thegroupareinformedaboutwhetheror not thedayis actuallyreserved.

The othersHandler takescareof the requestsfrom othercalendarsys-

Page 241: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

230 NONDETERMINISTICALTERNATION

othersHandler: @ | system(# start: @port;

day: @integer;reserve: @start,entry

(# d: @integer;enter ddo (if (days[d->day]=free)- >ok

//true then tmpBooked->days[d]if)

exit ok#);

end: @port;confirm: end.port

(# ok: @booleanenter okdo (if ok//true then booked->days[day]

else free->days[day]if)#);

do cycle(# start.accept; end.accept #)#)

Figure15.3 TheothersHandler of thedistributedcalendar.

tems. The reserve operationhandlesan initial reservation requestfrom an-othercalendar. It mayimmediatelyreturnfalseif thedayis notfree,otherwiseit will makea temporaryreservation.Theconfirm operationeitherbooksthedayor freesthetemporaryreservation,dependingon theenterparameter.

The Calendars pattern will not be given in detail. It representsaset of Calendar objects. It has a scanoperationwith the index variabletheCalendar thatiteratesoverall membersof theset.

Theelementsof therepetitiondays mayhavethevaluesfree , tmpBookedor booked . Thesevaluesmaybeimplementedasintegervalues.

Page 242: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

15.3 BOUNDEDBUFFER 231

(# Buffer: System(# S: [S.range] @char; in,out: @integer;

InPort,OutPort: @Port;Put: InPort.entry

(# ch: @charenter chdo ch->S[in]; (in mod S.range)+1->in#);

Get: OutPort.entry(# ch: @chardo S[(out mod S.range)+1->out]-> chexit ch#);

PutHandler: @ | System(#do Cycle(#

do (if in // out then Pause {Buffer is full}else InPort.accept; {accept Put}

if)#)#);GetHandler: @ | System

(#do Cycle(#

do (if in // (out mod S.range +1))then {Buffer is empty}else OutPort.accept; {accept Put}

if)#)#)do 1->in; S.range->out;

alt(#do PutHandler.start; Gethandler.start #)#);

Prod: @ | System(# ... ch -> Buf.Put; ... #);Buf: @ | Buffer;Cons: @ | System(# ... Buf.Get->ch; ... #)

do conc(#do Prod.start; Buf.start; Cons.start #)#)

Figure15.4 Boundedbuffer with alternatingcomponents.

15.3 Boundedbuffer

The examplein Figure15.4 describesa boundedbuffer implementedusingalternation. The internalcomponentsPutHandler andGetHandler controlcommunicationwith the Buffer -system; PutHandler takes care of a se-

Page 243: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

232 NONDETERMINISTICALTERNATION

ExtendedBuffer: Buffer(# GetRear: OutPort.entry

(# ch: @chardo S[(in+S.range-1) mod S.range -> in] -> chexit ch#);

#)

Figure 15.5 Extendedbuffer.

quenceof Put -communications,and GetHandler takes careof a sequenceof Get -communications.

TheimperativePause specifiesthatthis is a point whereinterleaving maytakeplace.Pause is not specifiedhere,but maybeimplementedasacommu-nicationwith somesystemin theenvironment,suchasa timer-system.

Sincethe executionof the PutHandler andGetHandler componentsisalternating,eachcomponenthasexclusiveaccessto thebuffer representation.Interleaving may only take placeat InPort.accept , OutPort.accept andPause .

In Figure 15.5 a sub-patternof Buffer is defined. A new operation,GetRear , for also taking elementsout from the rearof the buffer is added,showing that it is possibleto addoperationsto a port, andtherebyspecializetheprotocolof Buffer .

15.4 A simple game

Considera very simple gamebetweena playerand a ‘gameprocess.’ Thegameprocessis either in an even or an odd state. If the playerprobesthegameprocesswhenit is in anevenstate,theplayerlosesandthescoreis de-creasedby somevalue.If thegameprocessis in theoddstate,theplayerwinsandhis/herscoreis increasedby somevalue. At random,the gameprocessmaychangestate,from evento oddor from oddto even.Also, thegamepro-cessmay changethe valueby which the scoreof the player is increasedordecreased.The changeof stateandincrementvalueis initiated by a demonprocess.The gameprocessis thusconstantlyinvolved in a communicationsequencewith theplayerandthedemonprocess.

A concurrentsystemrepresentinga game-system,demon-systemand aPlayer -systemis describedin Figures15.6 and 15.7. Figure 15.6 showstheoverall structureof theconcurrentsystem,includingdetailsof thedemon-systemand the player -system. The game systemconsistsof two internal

Page 244: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

15.4 A SIMPLE GAME 233

system(# game: @ | system

(# odd: (#exit 1 #); even: (#exit 0 #);state,score,inc: @integer;playerHandler: @ | system(# ... #);demonHandler: @ | system(# ... #);

do alt(#do playerHandler.star t; demonHandler.start #)#);

demon: @ | system(#do cycle

(# score: @integerdo game.demonHandler .bu mp; random->pause;

(if random mod 2 // 1 thengame.demonHandler.c hange Inc ->s co re;(if score<100//true then

1->game.demonHand ler .se tIn celse 10->game.demonHand ler .se tI nc

if)if)#)#);player: @ | system

(#do game.playerHandle r.s tar tGa me; ...

game.playerHandle r.p rob e;. ..game.PlayerHandle r.e ndGame

#)do conc(#do game.start; demon.start; player.start #)#)

Figure15.6 Overall structureof simplegamesystem.

alternatingsystems,playerHandler anddemonHandler . Thedetailsof thesetwo systemsareshown in Figure15.7.

TheplayerHandler handlescommunicationwith theplayerandmaybein oneof threestates:start , playing andfinal . Eachstateis representedby a port . In a start state,the startGame operationwill be accepted;ina playing state,the probe and endGame operationswill be accepted;in afinal state,score will beaccepted.

ThedemonHandler maybe in two states,P1 andP2, alsorepresentedbyports. In stateP1, thebump andchangeInc operationsareaccepted;in stateP2, thesetInc operationwill beaccepted.

Page 245: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

234 NONDETERMINISTICALTERNATION

playerHandler: @ | system(# start: @port; {initial state: accepting StartGame}

startGame: start.entry(#do 0->score; false->stopped; even->state; 1->inc#);

playing: @port; {playing state: accepting Result, EndGame}probe: playing.entry

(#do (if state

// even then score-inc->score// odd then score+inc->score

if)#);

endGame: playing.entry(#do true->stop #);final: @port; {final state: accepting score}score: playing.entry(#do {display final value of score} #);stop: @boolean

do start.accept;play:

(#do playing.accept; (if stop//false then restart play if)#);

final.accept#);

demonHandler: @ | system(# P1: @port;

bump: P1.entry(#do (state+1) mod 2 -> state #);changeInc: P1.entry

(# v: @integer do score->v; true->newInc exit v #);P2: @port;setInc: P2.entry(# v: @integer enter v do v->inc #);newInc: @boolean

do cycle(#do P1.accept;

(if newInc//true then P2.accept; false->newInc if)#)

#);

Figure15.7 Detailsof playerHandler anddemonHandler .

Page 246: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

15.5 NOTES 235

The demon is representedby a concurrentsystemthat performsa bumpoperationon thegameat irregular intervals (controlledby a randomnumbergenerator, not shown here). Sometimesthe demon informs the gamethat itwantsto changethevalue(inc ) usedto increment/decrementthescore.Theactualchangeof this valueis dependenton the currentscore(score ) of theplayer.

Theplayeris alsorepresentedbyaconcurrentsystemthatperformsvariousoperationson game.playerHandler .

15.5 Notes

A programdescribinga numberof concurrentprocesseswill usuallyinvolvenondeterminism.This is the casesincethe speedof independentprocessescannotbe predicted.Several different languagemechanismshave beenpro-posedto dealwith nondeterminism,including theguardedI/O commandsofCSP, which alsoappearin Ada. GuardedI/O commandsintroducenondeter-minism into a singlesequentialprocess.Alternatingexecutionmay be seenasanalternative to guardedcommands.Insteadof having nondeterminismineachsystemobject,thenondeterminismis describedasalternatingtheexecu-tion of componentobjects.

By usingalternationandcompoundobjectsinsteadof guardedcommands,logically independentactionsequencesaremixed into oneactionsequence.This may make the structureof the resultingprogrammore clear. In addi-tion, it simplifiesimplementation.A CSP-processandanAda-taskmayhaveseveralopenchannelsof communicationwaitingatonetime. Whenacommu-nicationtakesplaceit is possiblethatotheropenchannelsof communicationof the objectsinvolved mustbe closed. In BETA, eachobjectmay wait forat mostonecommunication.No openchannelof communicationneedsto beclosedwhena communicationtakesplace. Finally, in CSPandAda the useof input and output as guardsis not symmetric: it is only possibleto haveinput-commands(accept-statements)in a guardedcommand.Thepossibilityof allowingoutput-commandsasguardsin CSPis mentionedin (Hoare,1978).However, symmetricuseof input-/output-guardsgreatlycomplicatesthe im-plementation.

Technically, mostprogramsusingalternationcould be simulatedby pro-gramsusingconcurrency, but concurrency implies thateachsystemexecutesactionswith a positivespeed.On a singleprocessorthis impliestime sharingusinga clock. Someimplementationsof concurrency avoid this by shiftingto anotherprocessonly at a point of communication.If this is the case,theprogramactually consistsof alternatingcomponentsand not of concurrentsystems.In aconcurrentprogramno loopingsystemcanmonopolizethepro-cessor, whereasthis is thecasewith analternatingprogram.

Page 247: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

236 NONDETERMINISTICALTERNATION

Alternationis notanalternativeto concurrency, but asupplement.A num-berof activitiesare,by theirnature,alternatingandnondeterministic,andsuchactivitiesshouldnotbemodeledby concurrentsystems,coroutinesor guardedcommands.

Page 248: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 16

Exception Handling

A largepartof any softwaredesignis thehandlingof errorsituationsor raresituationsthat are unlikely to happen. Considerthe Register example inFigure5.2. A registercanhold up to 100 integers. If an attemptis madetoinsert more than 100 integersusing the Insert patternthereis a problem.At the point of the commentH Overflow I , somecodefor dealingwith thissituationmustbeinserted. For ‘small’ programsit is commonto print anerrormessageandterminatetheprogramexecution.Theusermustthenincreasetheconstant100,recompiletheprogramandexecuteit again.

For mostnon-trivial programsit is not satisfactory just to terminatetheprogramwith an error message.Considerthe situationwherethe register ispartof awordprocessorprogram.An errormessagesayingthatsomeinternalregisterhasoverflowedis in generalnot meaningfulto a userof sucha wordprocessor. Furthermore,theuserwill not beableto increaseconstantsof pos-sible tables. Anotherexampleis a flight reservation system.Sucha systemrunsovera very long periodof time,andit would not beacceptableif a tableoverflow simply resultedin anerrormessageanda subsequentterminationoftheprogram.

The programfragmentusing the Register patternmay of coursekeeptrack of how many elementsarestoredin a givenRegister objectandthentake somespecialactionif morethan100 elementsareto be inserted.Thismay, however, imply that the programis greatlycomplicatedwith codethattestsfor suchraresituations.The codefor the ‘normal’ situationsmay thenbe difficult to read. It would be desirableif the codefor handlingthe ‘rare’situationscouldbeseparatedfrom thecodehandlingthe‘normal’ situations.

Therearemany typesof errorsor exceptionalsituationswhich a programmay have to dealwith. An exceptionis a classof computationalstatesthatrequiresanextraordinarycomputation.It is not possibleto giveaprecisedef-inition of whena computationalstateshouldbeclassifiedasanexceptionoc-currence; this is adecisionfor theprogrammer. In practice,mostpeoplehavea good feeling of what is the ‘main’ computationandwhat areexceptional

237

Page 249: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

238 EXCEPTIONHANDLING

situations.Theexceptionalsituationsareall thosesituationswhich imply thatthe‘main’ computationfails. Thefollowing is a list of examplesof situationsthatareoftenconsideredexceptional:

Overflow of tables The exampledescribedabove with tableoverflow in aRegister objectis typical for a largenumberof situations.Most soft-warehasobjectswith finite tablesthatmayoverflow.

UndefinedresultsA procedureor functionmaynothaveawell definedresultfor all possibleinput parameters.Oneexampleof this is division byzero,andanotheris a procedurefor invertinga matrix. If thematrix issingular, thentheinverseis notwell defined.

Incorr ect usageby the user A userusingaprogramor applicationin aner-roneousway is oneexampleof gettingundefinedresults.Giving wronginput to a programis a commonmistake madeby users. In somesit-uationsthis could be treatedasan exception,but in many situationsaprogramtaking complex input is equippedwith an input checker. Acompiler is an exampleof this. In othersituationsit shouldbe an ex-plicit partof theuserinterfacedesign.

Inconsistentdata Programsoftencommunicateby meansof files: onepro-gramwrites a file to be readby anotherprogram. The informationonthe file may thenbe written in a formatagreeduponby the authorsofthe two programs.The datafile couldbe inconsistentfor a numberofreasons:therecouldbeerrorsin thefirst program,someotherprogramcould have manipulatedthe file, by mistake someother file could beusedasinput to thesecondprogram,etc.

A documentsaved by a word processoroften hasspecialinformationusedby theword processor. It shouldbeableto handlepossibleincon-sistenciesin this file.

Operating systemerrors Considera word processor. Whena documentissaved, it maybe that thereis no moredisk space.Theusermay try toopena documentwhich cannotbe interpretedby the word processor.Theusermayattemptto modify a documentownedby anotheruser. Ifthewordprocessordoesnothandlesuchsituations,theoperatingsystemwill usuallyterminatetheword processorwith anerrormessagewhichmaynotbemeaningfulto theuser.

Languagedefinederrors Run-timeerrorssuchasindex errorsandattemptsto useNONEreferencesmayappearin evenwell testedprograms.Sincesuchsituationsappearbecauseof errorsin theprogram,it is in generaldifficult to recover from sucherrors. However, the programshouldatleastterminatewith aninformativemessage.

Page 250: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16.1 SIMPLEEXCEPTIONS 239

Numeric errors Computersonly supportnumberswith a finite amountofvalues.This meansthattheresultof anarithmeticoperationmayresultin anumberwhich cannotberepresentedby thehardware.This kind ofarithmeticoverflowis anexampleof anexception.

A programmustbe able to dealwith exceptions. A gooddesignrule is tolist explicitly the situationsthat may causea programto breakdown. Manyprogramminglanguageshavespecialconstructsfor describingexceptionhan-dling. In BETA, exceptionhandlingis usuallydescribedby meansof virtualpatterns.Thepurposeof thischapteris to show how to usevirtual patternsforexceptionhandling.

Fromtheabove discussionanexceptionhandlingmechanismshouldpro-vide thefollowing support:

Meaningful error messagesAs a minimumit shouldbepossibleto providemeaningfulerrormessageswhenanexceptionoccurs.

Recovery The programusingan objectshouldbe provided with the possi-bility to recover from anexceptionraisedby theobject.Sometimestherecovery will be transparentin thesensethat the ‘normal’ controlflowmaycontinue.In othersituationstherecovery mayimply a terminationor restartof partof thecomputation.

Separation of control flow The codefor dealingwith an exceptionshouldbeisolatedfrom thecodehandlingthe‘normal’ casesoasnot to disturbthe readability. Also an explicit indicationof possibleexceptionsmaybeausefulpropertyof aprogram.

In the following sections,a techniquefor using virtual patternsfor excep-tion handlingwill be presented.We startby introducinga simpleversionofexceptionpatternsandshow how thesemaybeusedfor overridingerrormes-sagesand for doing recovery from the exceptions(Sections16.1–16.3). InSection16.4thedifferencebetweenassociatingexceptionswith classpatternsandprocedurepatternsis described.Systemexceptionsandlanguage-definedexceptionsare describedin Sections16.5 and16.6, respectively. Finally, amoreadvanceddesignof exceptionpatternsis describedin Section16.7.

16.1 Simpleexceptions

In this sectiona simple useof exceptionpatternsis shown. ConsidertheRegister pattern in Figure 16.1 (it is a slightly revised version of theRegister patternfrom Chapter5, Figure5.2). The Register patternis ex-tendedwith two exceptionpatterns.Overflow is invoked whenthe registeroverflows, and NotFound is invoked when an attemptis madeto deletea

Page 251: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

240 EXCEPTIONHANDLING

key which is not in the register. Thesetwo exceptionsrepresenttwo differ-entclassesof exceptions:theOverflow exceptionis fatal in thesensethat itis probablynot meaningfulto continuetheprogram;theNotFound exceptionmayperhapsbeanerror. For many applicationsof Register it maynotbeanerror to attemptto remove anelementthat is not in theregister. Both excep-tion patternsaresub-patternsof the Exception pattern,which describesthegeneralpropertiesof exceptions.Exception will bedefinedbelow.

Consideranapplicationthathasaregisterof registrationnumbersof somekind. TheobjectRegistrations representsthis register. TheOverflow ex-ceptionis handledandtheapplicationterminates,but it overridesthedefaulterrormessagewith onethat is moremeaningfulfor theuser. The NotFoundexceptionis not consideredfatal, but a messagedescribingthe event is dis-playedto the user. The executionof an Exception instancewill by defaultresultin terminationof theprogramunlessaContinue hasbeenexecuted.Ascanbeseen,anexplicit Continue is executedby NotFound :

Registrations: @Register(# Overflow::<

(#do ’Too many registration numbers.’->msg.append;

’Program terminates.’->msg.append#);

NotFound::<(#do ’Attempt to delete:’ ->PutText;

key->screen.putInt;’which is not in the register’->PutText;Continue

#)#)

Page 252: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16.1 SIMPLEEXCEPTIONS 241

Register:(# Table: [100] @integer; Top: @integer;

Init: (#do 0->Top #);Has: {Test if Key in Table[1:Top]}

(# Key: @integer; Result: @boolean;enter Keydo ...exit Result#);

Insert: {Insert New in Table}(# New: @integerenter Newdo (if (New->&Has) // False then {New is not in Table}

Top+1->Top;(if (Top<=Table.Range)

// True then New->Table[Top]else

Overflow {An Overflow exception is raised}if)if)#);

Remove: {Remove Key from Table}(# Key: @integerenter keydo (Search:

(for inx: Top repeat(if Table[inx] // Key then

{remove key}leave Search

if)for);key->NotFound; {A NotFound exception is raised}

:Search)#);Overflow:< Exception

(#do ’Register overflow’->msg.Appen d; INNER #);NotFound:< Exception

(# key: @integerenter keydo key->msg.putInt;

’ is not in register’->msg.Appen d;INNER

#);#)

Figure16.1 PatternRegister with exceptionpatterns.

Page 253: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

242 EXCEPTIONHANDLING

TheException patternmaybedefinedasfollows:

Exception:(# msg: @text;

cont: @boolean;Continue: (# do true->cont #);Terminate: (#do false->cont #)

do ’Program execution terminated due to exception’->msg;

INNER;(if cont//false then

msg->PutText;{Terminate program execution}

if)#);

The text objectmsg is supposedto hold a text to bedisplayedto theuserincasetheexceptionleadsto terminationof theprogram.Themsg text is givena default valuein the exceptionpattern. In sub-patternsof Exception , it ispossibleeitherto appendmoretext to themessageor overridethemessage.IntheRegister patternmoretext is appended.In theinstanceRegistrations ,the messageis overriddenin the Overflow pattern,whereasit is not usedinNotFound asthisexceptioncontinuesexecution.

The default actionof an exceptionis to terminateexecution,but this ter-minationmaybe avoidedby specifyingan explicit Continue . The rationalebehindthis is thatanexceptionis anerrorthatmustexplicitly bedealtwith bytheprogrammer.

In the above example, NotFound is not consideredto be an error forRegistrations . This will probably be the case for most instancesofRegister . Also, it may not even be necessaryto display a message,i.e.NotFound will be ignored. Eachsuchinstanceof Register must,however,explicitly call Continue for NotFound . It would be moreconvenientif theprogrammerdid not have to specifya handlerin thesecases.To do this, itmustbe specifiedwithin Register that the default for NotFound will be tocontinueexecution.This canbedoneby insertinga call to Continue withinthe descriptionof NotFound in Register . The call to Continue shouldbeinsertedbeforeinner , sincethesub-patternsof NotFound areableto overridethecontinueby executionof Terminate .

A virtual patterndealingwith anexceptionis calledanexceptionpattern,or justanexception. Theinvocationof anexceptionpatternis calledanexcep-tion occurrence. An exceptionis saidto beraisedwhenanexceptionpatternisinvoked. Theobject-descriptorassociatedwith anexceptionpatternis calledahandleror anexceptionhandler.

An exceptionpatterndefinedin apatternwill bethedefaulthandlerfor the

Page 254: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16.2 RECOVERY 243

exceptionin thecasewherenofurtherbindingof it is made.A sub-patternmayextendthe default handlerby a further binding. A specificinstancehandlermaybeassociatedwith eachinstanceby instantiatinga singularobjectwith afurtherbindingof theexceptionpattern.

16.2 Recovery

Thehandlerassociatedwith Overflow in Registrations providesa new er-ror message,whereafterthe programexecutionis terminated. The handlercould insteadexecutea Continue , implying that the correspondingelementwould not be insertedin the table. Often thehandlermaybeableto recoverfrom theexceptionandcontinuetheexecutionasif theexceptionhadnot ap-peared.In theregisterexampleit might bepossiblefor thehandlerto removesomeof the elementsfrom the table, move someelementsto anothertableor extendthesizeof the table. Whetheror not this is possiblewill of coursedependon theactualusageof theRegister .

In BETA it is actuallypossibleto extendthesizeof a repetition.An eval-uationof theform:

25->Table.extend

will extendTable by 25 elements.An overflow handlerfor Register couldthenbedefinedasfollows:

Register:(# Overflow:< Exception

(#do Continue;

INNER;(Table.range div 4)->Table.extend

#);Insert:

(# New: @integerenter Newdo (if (New->&Has) // false then

{New is not in Table}Top+1->Top(if (Top<=Table.Range)

//false then Overflowif);New->Table[Top]

if)#);...

#)

Page 255: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

244 EXCEPTIONHANDLING

Thedefaulthandlerfor Register will executeaContinue andextendthesizeof Table by 25%. A furtherbindingof Overflow mayoverridetheeffect ofcontinue. Also notethe changein Insert : if control is returnedto Insertafter the executionof Overflow , it is assumedthat the exceptionalsituationhasbeenrepairedby thehandler, i.e. Insert maycontinue.

16.3 Partial recovery

Often it is not possibleto do the simplekind of recovery mentionedin theprecedingsection.It maybenecessaryto interruptthecontrolflow andescapeto anouterlevel in orderto do the recovery. To do this theremustbea welldefinedcontrolpoint thatcanbeusedto breakthecurrentcomputation.Sucha controlpoint canbedefinedasa label,andthehandlermaythenexit to thislabelby meansof leave or restart , asillustratedin thenext example:

do ...L: (# R: @Register(# Overflow::<(#do ... leave L #)#)

do ... I->R.Insert; ...#);

...

In thecaseof anOverflow beingraisedby Insert , theexecutionof theobjectcontainingthedeclarationof R is terminated.This is adrasticwayof handlingthe exception,sincethe R register including all its elementsis abandoned.However, in many situationsit is abetteralternativethanterminatingtheentireprogramexecution.

In somesituationsthehandlermaybeableto make a partialrecovery andrestartthecomputationfrom somepoint. This would correspondto replacingleave with restart in theaboveexample.An exampleof thiskind of partialrecovery is givenbelow.

16.4 Handlers for procedurepatterns

Theabove exampleshave shown examplesof associatinghandlerswith classpatterns.Suchhandlerswill be thesamefor all activationsof procedurepat-ternsassociatedwith theobject,i.e. thecodemayhaveseveralinvocationsof,for example,Insert , andexceptionsraisedby all theseInsert swill havethesamehandler. In many situationsit would bedesirableto associatedifferenthandlerswith thedifferentinvocations.This is possibleby defininganexcep-tion patternasanattributeof Insert . Considerthe following descriptionofRegister :

Register:

Page 256: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16.4 HANDLERS FORPROCEDUREPATTERNS 245

(# ...Insert: {Insert New in Table}

(# Overflow:< {Procedure level exception}Exception(# ... #);

New: @integerenter Newdo (if (New->&Has)

// false then {New is not in Table}Top+1->Top(if (Top<=Table.Range)

// false then Overflow if);New->Table[Top]

if)#);Overflow:<

Exception(# ... #); {Class level exception}#)

Handlersfor differentinvocationsof Insert maynow bedefinedasfollows:

(# R: @Register(# Overflow::<(# ... #); {Class handler for R} #)

do ...I->R.Insert

(# Overflow::<(# ... #); {Procedure handler} #)...J->R.Insert

(# Overflow::<(# ... #); {Procedure handler} #)...

#)

It mayappearthatthereis nousefor theclasshandlersinceonly theprocedurehandlersassociatedwith Insert will becalled.However, thelocal procedurehandlersmayinvoke theclasshandlerif they areunableto dealwith thesitu-ation:

I->R.Insert(# Overflow::<(#do ... R.Overflow #) #)

The situation where an exception handler invokes an enclosinghandleriscalledexceptionpropagation.

Sometimesit is desirableto automaticallypropagateanexception. In theabove exampletheremaybea mixtureof invocationsof Insert wheresomehavea localprocedurehandlerandothersdonot. For thosewhichdonothaveaprocedurehandlerit wouldbedesirablefor theexceptionto beautomaticallypropagatedto theclasshandler. This couldbespecifiedin thedeclarationoftheexceptionin Insert :

Page 257: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

246 EXCEPTIONHANDLING

Register:(# Overflow:<(# ... #);

Insert:(# Overflow:< Exception

(#do INNER;

(if {no binding of Overflow} thenthis(Register).Overflow

if)#)

...#)

...#)

The ideais that if no bindinghasbeenmadeof Overflow in a possiblesub-patternof Insert , thenthe Overflow exceptionof the enclosingRegisterpatternis invoked.In Section16.7it is shownhow to implement‘no bindingof Overflow’ .

16.5 Systemexceptions

Any implementationof BETA, includingtheMjølnerBETA System,will pro-vide librariesof patternsandobjectsfor interfacingto theunderlyingoperat-ing system.A goodexampleof this is aFile patternfor interfacingto thefilesystemof thecomputer. A largenumberof errorconditionsmayappearwhenmanipulatingfiles. Below a simpleversionof a file1 patternis given,togetherwith possibleexceptionsthatmayberaised.

File:(# name: @text; {The logical name of the file}

Open:{General super-pattern for OpenRead and OpenWrite}(# OpenError: FileException

(#do ’Error during open.’->msg.append; INNER#);

NoSuchFile:< OpenError(#do ’No such file.’->msg.append; INNER

1This is a simplified version of the File patternimplementedby the Mjølner BETASystem.

Page 258: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16.5 SYSTEMEXCEPTIONS 247

#)enter namedo INNER#);

OpenRead: Open(# NoReadAcess:< OpenError

(#do ’No permission to read.’->msg.append;

INNER#)

do {open the file for read}{May raise NoSuchFile or NoReadAccess}

#);OpenWrite: Open

(# NoReadAccess:< OpenError(#do ’No permission to write.’->msg.append;

INNER#)

do {Open this(File) for write}{May raise NoSuchFile or NoReadAccess}

#);Get:

(# ch: @chardo {Get next char to ch}

{May raise EOFerror}exit ch#);

Put:(# ch: @charenter chdo {Write ch to file}

{May raise DiskFull}#);

Close: (# do {close the file} #);Remove: (# do {Remove the file from the disk} #);FileException: Exception

(#do ’Error in file:’->PutText; name->PutText;INNER

#);DiskFull:< FileException

(#do ’No more space on disk’->msg.append;INNER

Page 259: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

248 EXCEPTIONHANDLING

#);EOFerror:< FileException

(#do ’Attempt to read past end-of-file’->msg.append;

INNER#)

#)

Thenormaluseof a File maybeasfollows:

(# F: @Filedo {Prompt user for file name}

N->F.openWrite;...ch->F.put;...F.close

#)

In the following example,handlersare definedfor someof the exceptions.When DiskFull is raised,the file is closedand removed, and the programterminatesexecution. If the file cannotbe opened,or the userhasno writepermissionto thefile, theuseris askedto try again:

(# F: @File(# DiskFull::<

(#do ’Please remove some files from the disk’

->PutText;close; Remove; {Close and remove the file}

#)#)

do GetFileName:(#do {Prompt user for file name}

N->F.openWrite(# NoSuchFile::<

(#do ’File does not exist. Try again’

->PutText;Restart GetFileName

#);NoWritePermission::<

(#do ’You do not have write permission’

Page 260: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16.6 LANGUAGE-DEFINEDEXCEPTIONS 249

->PutText;’Try again’->PutText;restart getFileName

#)#)#);

...ch->F.put;...F.close

#)

16.6 Language-definedexceptions

Language-definedexceptionshave to be dealtwith by providing pre-definedpatternsin the environment. An implementationof BETA could provide apre-definedpattern,Program , that hasvirtual patternscorrespondingto allpre-definedlanguageexceptions.TheProgram patterncouldbedescribedasfollows:

Program:(# IndexError:< Exception

(#do ’Index out of range’->msg.append;

INNER#);

RefIsNone:< ...ArithmeticOverflow:< ...DivisionByZero:< ...

do INNER#)

A BETA programmaythenprovide handlersfor thelanguage-definedexcep-tionsasshown in thefollowing example:

Program(# IndexError::< (# ... #);

RefIsNone::< (# ... #);ArithmeticOverflow::< (# ... #);DivisionByZero::< (# ... #);...

do ...#)

Page 261: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

250 EXCEPTIONHANDLING

TheaboveProgram provideshandlersfor all four kindsof exceptions.It is possibleto provideseverallevelsof Program objectsin orderto have

differenthandlers,for example,for IndexError in differentpartsof thepro-gram.This is illustratedin thefollowing example:

Program(# IndexError::< (# ... #);

RefIsNone::< (# ... #);ArithmeticOverflow::< (# ... #);DivisionByZero::< (# ... #);...

do ...Program(# IndexError::< {alternative handler for index error}

(# .. #)do ...#)

#)

In the do-partof the outermostdescriptora new handlerfor index error isprovided.Thishandlerwill thenhandlepossibleindex errorsin theinnermostProgram object.

Theproblemwith this approachis thata handlermustbesuppliedfor allthelanguage-definedexceptions,sincethehandlersin theoutermostProgramobjectarenot automaticallyinvoked for exceptionsotherthan IndexError .In thenext section,amoreadvancedexceptionmechanismis provided,whichmakesit easierto propagateexceptionsfrom an inner Program object to anouterProgram object.

16.7 Advanceddesignof exceptionpatterns

In this section,a possibledesignfor a moreadvancedexceptionmechanismis presented.Thegoal is to defineanexceptionhandlingmechanismwith thefollowing properties:

G Bettersupportfor thepropagationof language-definedexceptionsthathavenohandlerto apossibleouterProgram object.

G It shouldbepossibleto specifyanotherterminationlevel asa default. ThesimpleException pattern(from theprevioussections)terminatestheentireprogramexecutionasadefault action.

G Whenan object level is terminated,it shouldbe possibleto specifysome‘clean-up’actionsto beexecutedbeforeterminationto ensuresmoothter-mination.

Page 262: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16.7 ADVANCED DESIGNOFEXCEPTIONPATTERNS 251

This is achievedby combiningtheException patternwith theProgram pat-ternin thefollowing way:

Program:(# Exception:

(#msg: @text;cont: @boolean;Continue: (# do true->cont #);Terminate: (# do false->cont #)

do ’Program execution terminated due to exception’->msg;

INNER;(if cont//false then

(if outerMostProgram then msg->PutText if);CleanUp;leave Program

if)#);

CleanUp:<(#do INNER #);IndexError:< Exception

(#do (if {No binding} then

(if Outer[]<>NONE // True thenOuter.IndexError if)if)

’Index out of range’->msg.append;INNER

#);RefIsNone:< ...ArithmeticOverflow:< ...DivisionByZero:< ...Outer: ˆProgram;DefineOuter:<(#do INNER #)

do DefineOuter;INNER

#);

Theexceptionpatternsmaybeusedasfollows:

(# Main: Program(# IndexError::< (# ... #);

RefIsNone::< (# ... #);do ...

L0:Program

Page 263: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

252 EXCEPTIONHANDLING

(# IndexError::< (# ... #){New handler for index error}

DefineOuter::<(#do Main[]->Outer[] #){Propagate other exceptions}{to handlers in Main}

CleanUp::<(#do {executed before termination}

{of this(Program)}#)

do ...L1:

(# Register: (# ... #)do L2:

(# Registrations: @Register(# Overflow::< (# do ... #);

NotFound::< (# do ... #)#)

do ...#);

...#);

...#)

#)do Main#)

Theoptionsfor thehandlersof Overflow andNotFound in Registrationsare:

(1) Do nothing: in this casethe exceptionwill imply a terminationof theenclosingProgram objectof theRegister definition,i.e. L0 will termi-nate.

(2) Explicit leave : the exceptionhandlermayexplicitly specifya leave ofanarbitraryenclosinglevel (e.g.L2, L1, L0 or Main ).

(3) Explicit Restart : thehandlermayspecifya restartof anenclosinglevel(e.g.L2, L1, L0 or Main ).

(4) Explicit Continue : the handlermay executeContinue andtherebyre-sumeexecution.

The Program patternhasattributesfor supportingpropagationfrom inner toouterProgram objects.The Outer andDefineOuter attributesareusedforspecifyinga Program objectfor propagationof exceptionsthathave no han-dlers. Sub-patternsof Program canhave a further binding of DefineOuter

Page 264: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

16.8 EXERCISES 253

for specifying an outer Program object. This mechanismassuresthat alllanguage-definedexceptionsexcept IndexError are propagatedto the out-ermostProgram object.

In someof the above examples,thereis a needto testwhetheror not avirtual patternhasactuallybeenboundin sub-patterns.This is possibleusingpatternvariables.Considerthefollowing example:

T: (# V:< D;D:

(#do ...

INNER;(if V## // D## then {No further binding} if)

#)#)

This is only possibleusing the above form of virtual specification. For theshorthandform:

V:< (# do ... INNER ... #)

it is not possible,sinceV## will refer to the actualbindingof V. This meansthatwehaveto modify someof theException patternsin theaboveexamples.It is possibleto imaginea moreexplicit supportin BETA for testingwhetheror not a virtual patternhasa furtherbinding. This maybe includedin futureversionsof BETA.

16.8 Exercises

(1) RedoExercise1 in Chapter11 suchthatanexceptionis raisedwhenR isnot qualified by T.

(2) Modify theRegister in Figure16.1suchthatanexceptionis raisedif anattemptis madeto insertanelementalreadyin theregister. Whatshouldthedefault behavior of this exceptionbe?

16.9 Notes

Thefoundationof exceptionhandlingis thepioneeringwork by J.B.Goode-nough(Goodenough,1975). Mostprocedurallanguageswith speciallanguagefacilities for exceptionhandlingaremoreor lessdirectly basedon this work(e.g. languageslikeClu andAda). Severalobject-orientedlanguageshave in-cludedspeciallanguagefacilitiesfor exceptionhandling(e.g.Smalltalk,EiffelandC++).

Page 265: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

254 EXCEPTIONHANDLING

All thesefacilitiesemploy a dynamicapproachto finding thehandlersofa particularexception. This implies (with variations)that the handlerfor anexceptionis found by traversingthe call chainof procedureinvocationsandenclosedblocksbackwards,until ablockor aprocedureinvocationis foundinwhich a handlerfor theexceptionis defined.This dynamicapproachimpliestheseparatedefinitionof theexceptionandthehandler, andassociationof theexceptionwith the handlerbasedon the dynamicbehavior of the program.This impliesthat it is very difficult to tracetheexceptionalcomputation(thisworks somewhat like a seriesof computedGOTOs), and it is very difficultto ensurethat all exceptionoccurrenceswill eventuallybe handled(i.e. it isvery difficult to verify that a programwill respondsensiblyto all perceivedexceptionalconditions).2

This dynamic behavior (dynamic binding of handlersto exceptions)isoften in contrastto the host language(e.g. Ada and Clu) that usesstaticnamebinding (e.g. when binding procedureinvocationsto proceduredec-larations). This hasresultedin criticisms from several sources,e.g.C.A.R.Hoare(Hoare,1981)statesthat ‘ ... theobjectivesof languagesincluding re-liability, readability, formality andevensimplicity ... havebeensacrificed...by a plethora of features... manyof themunnecessaryandsomeof them,likeexceptionhandling, evendangerous.’

As an alternative to the dynamicapproachto exceptionhandling,a pro-posalhasbeenmadefor a staticapproachto exceptionhandlingby JørgenLindskov Knudsen(Knudsen,1984; Knudsen,1987) that is basedon the se-quel conceptproposedby (Tennent,1977). A sequelis a unificationof con-tinuationsandproceduresin thesensethatit is likeaprocedure,exceptthatitdoesnot returnto thepoint of its invocation,but insteadterminatestheblockin which it is defined. Whenusedfor exceptionhandling,this implies thata sequelin onedefinition definesan exception,its handlerandthe termina-tion level of the exception(i.e. the enclosingblock). The advantageof thisapproachis that thesequelconceptfollows thestaticbindingrule of thehostlanguageandat the sametime allows for efficient exceptionhandling. Thestaticapproachhasbeenfurtherdevelopedto incorporatesupportfor smoothtermination(i.e. allowing for clean-up,etc.,of blocksbeingterminatedduringanexceptional‘backtrack’)(Knudsen,1987).

The BETA approachto exceptionhandlingis inspiredby this static ap-proachto exceptionhandling.Therationalefor theconcretedesignhasbeento introducestaticexceptionhandlinginto BETA without introducingany newlanguageconstructs,but insteadutilizing thepowerfulabstractionmechanismsof the languageto constructan exceptionhandlingconcept.Exceptionhan-dling asdescribedin this chapteris merelya techniquefor usingvirtual pat-terns.

2It is importantto notethatexceptionhandlingin any programminglanguageis only ca-pableof handlingexceptionalconditionsthathavebeenperceivedduringprogramdesign.

Page 266: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 17

Modularization

In previouschapterswe have introducedlanguagemechanismsfor describingobjectsandpatternsof a BETA programexecution. In this chapter, languagemechanismsfor describingthephysicalorganizationof BETA programswillbe introduced. A non-trivial BETA programwill usually consistof severalpages,so it is desirableto be able to split sucha descriptioninto smaller,moremanageableunits. Suchunitsarein generalcalledmodules. A moduleis a convenientpart of a programtypically kept in a file (or in a database),manipulatedby aneditor, andtranslatedby acompiler.

Modularizationis of the utmostimportancewhenwriting programsthataremorethansmall examples.Sincethe examplesmustbe fairly small in abook like this, it is difficult to adequatelyillustrateandmotivatemodulariza-tion. The languageconstructswill be introducedusingvery small examplesto illustrate the principles. The modularizationtechniquesdescribedbeloware absolutelynecessaryfor large programsand highly recommendedevenfor moderatelysizedprograms.The reasonsfor this may be summarizedasfollows:

G Most reasonablysizedprogramscanbeconvenientlysplit into modulesoflogically relatedelements,sinceit is cumbersometo handlelargeprograms.Large programsareeasierto understandif split into a numberof smallerunits.

G Whenediting it is easierto managea numberof smallmodulesinsteadofonelargeprogram.

G Whenseveralpeopleareworkingonaproject,eachpersoncanwork onhisown setof modules.

G Modulescanbe saved in a library andsharedby several programs.Goodmodularizationmechanismswill thusimprovereusabilityof codeaswell asdesigns.

G It is goodpracticeto split amoduleinto interfacemodules(oftenreferredtoasspecificationmodules) and implementationmodules. An interfacemod-

255

Page 267: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

256 MODULARIZATION

ule defineshow a modulecanbeused,andan implementationmodulede-scribeshow a moduleis implemented.This makes it possibleto preventusersof a modulefrom seeingdetailsaboutdatarepresentationandimple-mentationof algorithms.

G Certainmodulesmayexist in severalvariants. Oneexampleof this is dif-ferent implementationsof the same(interface)module. Anotherexampleis variantsof a modulecorrespondingto differentcomputers.If a modulehasseveral variantsit is importantthat the commonpart of two or morevariantsexists in only onecopy. It shouldonly be necessaryto separateout thecodethatdiffersbetweenvariants,otherwisemaintenancebecomesmorecomplicated,sincethesamechangemayhave to bemadefor severalvariants.

G A modulemaybeusedasaunit to beseparatelycompiled. Whenchangingpartsof a largeprogram,it is not acceptableto be forcedto recompilethewhole program,sincethis may take several hours. With separatecompi-lation of modules,only themodulesthathave beenchangedandthosethatareaffectedby thesechangeshaveto berecompiled.Below weexplainhowonemodulemaybeaffectedby changesin another.

In the following section,languageconstructsfor describingmodularizationareintroduced.Thereafter, wediscusshow to applytheselanguageconstructsandwhy they areusefulandnecessary.

17.1 Fragments

The languageconstructsfor describingprogrammodularizationarenot con-sideredpart of the BETA language.The reasonis that BETA is a languagefor describingobjectsandpatternsof a BETA programexecution, while themodularizationlanguageis for describingthephysicalorganizationof just theprogram. The structuringof the programexecutionin termsof objectsandpatternswill of coursealsobe reflectedin the program,but in addition theprogramitself maybeorganizedin modulesthatdo have to follow thestruc-turing in termsof objectsandpatterns.The two languagesarethusintendedfor quitedifferentpurposes.Themodularizationlanguageis calledthe frag-mentlanguage, sinceit describestheorganizationof BETA programsin termsof fragments. (Thenotionof a fragmentwill beintroducedbelow.) Thefrag-mentlanguageis usedfor communicatingwith TheFragmentSystem, whichis thecomponentof theMjølner BETA Systemthathandlesstoringandma-nipulationof fragments.The termsfragmentlanguage and fragmentsystemareusedinterchangeablywhenthis causesno confusion.

Thefragmentlanguageis independentof BETA. Theprinciplesbehindthefragmentlanguagecanin factbeusedto describemodularizationof mostpro-gramminglanguages.Thefragmentlanguageis grammar-based. Theideais

Page 268: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.1 FRAGMENTS 257

thatany correctsequenceof terminalandnonterminalsymbolsdefinedby thegrammaris alegalmodule.Thefragmentlanguagedescribeshow suchstringsmaybe combinedinto larger strings,andis presentedhereusinga graphicalsyntax,thoughthe fragmentlanguagealsohasa textual syntaxwhich is cur-rently usedby the Mjølner BETA System. A future versionof the MjølnerBETA Systemwill includesupportfor a graphicalsyntaxsuchasthatusedinthis book.1

17.1.1 Forms

TheBETA grammarin AppendixA hasthefollowing rule:

<ObjectDescriptor> ::= <PrefixOpt> <MainPart>

Thefollowing stringscanbederivedfrom thenonterminal<ObjectDescrip-tor> :

(1) (# T: @Text do ’Hello’->T #)

(2) (# P: <ObjectDescriptor>; R: ˆPdo (if <Evaluation> // true then &P[]->R[] if)#)

Thefirst stringconsistsonly of terminalsymbols.Thesecondstringhastwounexpandednonterminals,<ObjectDescriptor> and<Evaluation> . In Fig-ure 17.1,otherexamplesof stringsderived from nonterminalsof the BETAgrammarareshown.

A stringof terminalandnonterminalsymbolsderivedfrom a nonterminalA is called an A-form , or sometimesjust a form 2. The derived stringsinFigure 17.1 are all examplesof forms. Forms are the basicelementsusedto definemodulesin theMjølner BETA System.The fragmentlanguagehaslanguageconstructsfor combiningforms into completeprograms.Consider,for example,the forms 3 and4 in Figure17.1. By substitutingthe DoPartnonterminalof form 3 by form 4 wegetthefollowing form:

Foo: (# a,b,c: @integerenter(a,b)do a*b->cexit c#)

The fragmentlanguageis a notationfor describinghow nonterminalsin oneform maybereplacedby otherforms.

1In additionto theuseof agraphicalsyntax,thefragmentlanguagedescribedin thisbookis slightly moregeneralthanthe actualimplementation.For details,seethe Mjølner BETASystemmanuals.

2In formal languagetheorythis is calleda sententialform.

Page 269: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

258 MODULARIZATION

Nonterminal Examplesof derivedforms1. <Attributes> P: (# a,b: @integer #);

R: ˆP2. <AttributeDecl> X: @integer3. <PatternDecl> Foo: (# a,b,c: @integer

enter(a,b)<DoPart>exit c#)

4. <DoPart> do a*b->c5. <Imp> (if B//True then <Imp> if)6. (for <Index> repeat <IfImp> for)7. <IfImp> (if B//True then <Imp> if)8. <ForImp> (for <Index> repeat <IfImp> for)

Figure 17.1 Nonterminalsandexamplesof correspondingderivedforms.

17.1.2 Slots

A form maycontainseveralnonterminalshaving thesamesyntacticcategory.This is thecasein thefollowing form:

Stack:(# Push: (# e: @integer enter e <DoPart> #);

Pop: (# e: @integer <DoPart> exit e #)#)

which hastwo <DoPart> nonterminals.In thefragmentlanguageit is neces-saryto beableto referseparatelyto eachnonterminal.Eachnonterminalmustthereforehaveanamewhich uniquelyidentifiesit.

In theMjølner BETA System,severaltoolsmanipulateforms,thusnot allnonterminalsarenecessarilyto beusedby thefragmentsystem.Thenontermi-nalsusedby thefragmentlanguagearecalledslotssincethey defineopeningswhereotherformsmaybeinserted.They aremarkedby thekeywordSLOT. Anonterminaldefiningaslot hasthesyntax:

<<SLOT T:A>>

whereT is thenameof theslot andA is thesyntacticcategory. Also notethatslotsareenclosedby << and>> insteadof < and>. This is donepurely fortechnicalreasons.A nonterminalmustbegin with a symbol(here<<), whichis not in the vocabulary of the language.Since< is usedas less than inBETA, it cannotbeusedto begin anonterminal.

Theaboveform mayinsteadbedescribedasfollows:

Page 270: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.1 FRAGMENTS 259

Stack:(# Push: (# e: @integer enter e <<SLOT Push:DoPart>> #);

Pop: (# e: @integer <<SLOT Pop:DoPart>> exit e #)#)

Slot namesandBETA namesbelongto differentlanguages,thusthereis nopossibility of confusingBETA namesandslot names.In theabove examplethereis apatterncalledPush andaslotcalledPush . As weshallseelater, it isconventionalto useidenticalnamesin thismanner.

17.1.3 Fragment-form

In the fragmentlanguage,eachform mustbe givena nameandits syntacticcategory specified.A fragment-formis a form associatedwith a nameandasyntacticcategoryhaving thefollowing syntax.As notedearlier, thesyntaxofthefragmentlanguageis mainlygraphical:

F:Aff

F is the nameof the fragment-form,A is the syntacticcategory, and ff is aform, i.e. ff is a stringof terminalandnonterminalsymbolsderivedfrom A.

Thefollowing is anexampleof a fragment-form:

Counter:PatternDeclCounter:

(# Up: (# n: @integer enter n <<SLOT Up:DoPart>> #);Down: (# n: @integer <<SLOT Down:DoPart>> exit n #)

#)

17.1.4 Fragment-group

Often it is convenientto definea setof logically relatedfragment-formsto-gether. For this purposeit is possibleto definea groupof fragments,calledafragment-group, which hasthefollowing syntax:

Page 271: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

260 MODULARIZATION

NAME ’F’

F1:A1ff1

F2:A2ff2

...

Fn:Anffn

thatdefinesafragment-groupwith thenameF consistingof n fragment-forms.Thenameof fragment-formi is Fi , its syntacticcategory is Ai andtheactualfragment-formis ffi .

Thefollowing is anexampleof a fragment-group:

Up:DoPartdo n+7->n

Down:DoPartdo n-5->n

Thetermfragmentrefersto eithera fragment-formor a fragment-group.

17.1.5 Fragment library

Thefragmentsystemhandlesthestoringof fragment-groupsin alibrary, calledthe fragmentlibrary. The fragmentlibrary is usuallyimplementedon top ofthe computer’s file systemor databasesystem. The fragmentlanguagehasconstructsfor describinghow to combinefragmentsinto compoundfragmentsandeventuallycompleteprograms.Thefragmentlanguagerefersto fragment-groupsstoredin the fragmentlibrary by meansof a fragmentname(or justname). TheMjølner BETA Systemassumesa hierarchicalnamestructureinthestyleof UNIX directoriesor Macintoshfolders3, asshown in Figure17.2.

In theMjølner BETA System,fragment-groupsarerepresentedasfiles insuchadirectory. Thenameof a fragment-groupis givenby meansof aUNIX-pathenclosedin quotes(’ ). Thepath:

’/home/smith/CounterGroup’

denotesa file CounterGroup which is supposedto contain a fragment.CounterGroup residesin thedirectory/folder/home/smith . In thefollowingexamples,thenameof a fragment-groupwill oftenbegivenasshown below:

3Thereaderis assumedto havesomeknowledgeof suchhierarchicalfile systems.

Page 272: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.1 FRAGMENTS 261

/

home lib

smith jones beta tex

betaenv editor

Figure 17.2 Hierarchicaldirectorystructure.

NAME ’/home/smith/CounterGroup’

Counter:PatternDeclCounter:

(# Up: (# n: @integer enter n <<SLOT Up:DoPart>> #);Down: (# n: @integer <<SLOT Down:DoPart>> exit n #)

#)

For fragment-groupsconsistingof only one fragment-form,one shouldnot confusethe nameof the file/folder containingthe fragment-groupwiththe nameof the fragment-form. In the above example, CounterGroup isthefragment-group(andfile/folder) nameandCounter is thefragment-formname.Thefile/foldernameandthefragment-formnamemaybeidentical.

17.1.6 Origin of a fragment-group

The origin part of a fragment-groupspecifiesa fragment-groupthat is usedwhenbindingfragment-formsto slots.Considerthefollowing example:

NAME ’/home/smith/CounterBody’origin ’/home/smith/CounterGroup’

Up:DoPartdo n+7->n

Down:DoPartdo n-5->n

Page 273: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

262 MODULARIZATION

The origin of CounterBody is the fragment-group/home/smith/Counter-Group . The origin musthave free slotscorrespondingto Up andDown. Theorigin constructspecifiesthatthefragment-formsUp andDownaresubstitutedfor thecorrespondingslotsin CounterGroup . Theresultof thissubstitutionisa form, calledtheextentof thefragment,asdefinedbelow.

A fragmentdefinesa unique form, called the extent of the fragment.The extent of the above fragment is a combinationof CounterBody andCounterGroup . Thecombinationis obtainedby filling in theslotsin theori-gin with thecorrespondingfragment-forms.In theabove examplethis givesthefollowing form:

Counter:(# Up: (# n: @integer enter n do n+7->n #);

Down: (# n: @integer do n-5->n exit n #)#)

17.1.7 The basicenvir onment

TheMjølnerBETA Systemprovidesabasicenvironmentthatdefinesthemostimportantstandardpatternsandobjects.In addition,thisenvironmentinitiatesandterminatesthe executionof any BETA program. The basicBETA envi-ronmentis thefragmentbetaenv 4 shown in Figure17.3.As canbeseen,thisfragmentdefinesa numberof standardpatterns.In addition,thefragmenthastwo slots:PROGRAMandLIB .

A completeBETA programthatmakesuseof betaenv maybedefinedbydefiningthe PROGRAMslot. The following fragment-formis an exampleof averysimpleBETA program:

NAME ’mini1’origin ’betaenv’

PROGRAM:ObjectDescriptor(#do ’Hello world!’->PutLine#)

Theextentof thefragmentmini1 is thefollowing form:

{****** The basic BETA environment ******}(# ...

PutLine:...

4In the restof this chapter, simplenameswithout directorypathsareusedfor specifyingthenamesof fragment-groups.

Page 274: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.1 FRAGMENTS 263

NAME ’betaenv’

betaenv:ObjectDescriptor

{****** The basic BETA environment ******}(# Put: (# ch: @char enter ch ... #);

PutInt: (# n: @integer enter n do ... #);PutText: (# T: @Text enter T do ...#);NewLine: (# ... #);PutLine: (# T:@Text enter T do T->putText; newLine #);Text: ...;File: ...;integer: (# ... #);char: (# ... #);... {Definition of other standard attributes}<<SLOT LIB: Attributes>>

do {Initialize for execution}<<SLOT PROGRAM:ObjectDescrip tor >>;{Terminate execution}

#)

Figure17.3 ThebasicBETA environment.

...do {Initialize for execution}

(#do ’Hello world!’->PutLine#){Terminate execution}

#)

As canbe seen,the PROGRAMfragmenthasbeensubstitutedfor the PROGRAMslot in betaenv . In the PROGRAMfragmentit is thereforepossibleto useanynamewhich is visible at thepoint of thePROGRAMslot in betaenv . PutLineis visibleat thePROGRAMslotandis thereforevisible in thePROGRAMfragment.It would alsohave beenpossibleto make useof patternslike integer , char ,Text , etc. In Section17.6weshallreturnto thequestionof visibility.

The LIB slot in betaenv is intendedfor makinga setof generalpatternsto be usedby otherprograms.The differencebetweensucha library andaprogramis thatthelibrary is a list of patternswhereastheprogramis a singleobject-descriptor. Thefollowing exampleis anexampleof a library consistingof two patterns:

Page 275: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

264 MODULARIZATION

NAME ’mylib’origin ’betaenv’

LIB:attributesHello: (# do ’Hello’->PutText #);World: (# do ’World’->PutText #)

By substitutingthe LIB slot in betaenv with the LIB fragment-formweobtainthefollowing form:

{****** The basic BETA environment ******}(# ...

Hello: (# do ’Hello’->PutText #);World: (# do ’World’->PutText #)

do {Initialize for execution}<<SLOT PROGRAM:ObjectDescriptor>>;{Terminate execution}

#)

As canbe seen,the library patternsareinsertedat the point of the LIB slot.Thismeansthatin theLIB fragment-formit is possibleto seeall namesvisibleat thepoint of theLIB slot in betaenv .

Note that the extent of mylib is not an executableprogram,since thePROGRAMslot hasnot beendefined. In the next sectionwe shall show howto makeuseof a library in aprogram.

17.1.8 Include

Whenmakinglibrarieslike mylib , we needa mechanismfor combiningsev-eral fragmentsinto onefragment.The include constructmakesthis possible.In the following examplewe have a programthat makes useof the myliblibrary:

NAME ’mini2’origin ’betaenv’include ’mylib’

PROGRAM:ObjectDescriptor(#do Hello; World; newLine#)

The effect of the include ’mylib’ is that the patternsdefinedin myLibcanbeusedin the PROGRAMfragment-form.Formally the fragment-formsof

Page 276: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.1 FRAGMENTS 265

mylib becomepartof thefragmentmini2 . In theabove examplemini2 maybeunderstoodasa fragment-groupconsistingof thefragment-formsin myliband the PROGRAMfragment-form. This implies that the extent of mini2 isobtainedby substitutingthe LIB slot in betaenv by the LIB fragment-formin mylib andby substitutingthe PROGRAMslot in betaenv by the PROGRAMfragment-formin mini2 . Thisgivesthefollowing form asa result:

{****** The basic BETA environment ******}(# ...

Hello: (# do ’Hello’->PutText #);World: (# do ’World’->PutText #)

do {Initialize for execution}(#do Hello; World; newLine#){Terminate execution}

#)

Sincethepatternsin mylib areinsertedat thepoint of the LIB slot, they arevisible at thepoint of thePROGRAMslot. This is wherethePROGRAMfragment-form in mini2 is inserted,i.e. thepatternsHello andWorld arevisible insidethePROGRAMfragment-form.

A fragment-formmayhavemorethanoneinclude.Thismakesit possibleto useseverallibrary fragmentsin thesamefragment.

17.1.9 Body

When defining a fragmentit is often desirableto be able to specify oneormorefragmentsthatmustalwaysbeincludedwhenusingthefragment.Thisis oftenthecasewhena fragmentis separatedinto aninterfacefragmentandoneor moreimplementationfragments.Herewe introducethe constructforspecifyingthis, but delay further explanationuntil Section17.2. The bodyconstructspecifiesa fragmentthat is alwayspartof theextent. Considerthefollowing fragments:

NAME ’counter’origin ’betaenv’body ’counterbody’

LIB:Attrib utesCounter:

(# Up: (# n: @integer enter n <<SLOT Up:DoPart>> #);Down: (# n: @integer <<SLOT Down:DoPart>> exit n #);Private: @ <<SLOT Private:ObjectDescriptor>>

#)

Page 277: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

266 MODULARIZATION

The counter fragmenthasa body specificationwhich specifiesthat a frag-ment called counterbody is always part of the extent of counter . Thecounterbody fragmentcouldbedescribedasfollows:

NAME ’counterbody’origin ’counter’

Up:DoPartdo n+7->n

Down:DoPartdo n-5->n

Private:ObjectDescriptor(# V: @integer #)

Thecounter fragmentcouldbeusedby thefollowing fragment:

NAME ’mini3’origin ’betaenv’include ’counter’

PROGRAM:ObjectDescriptor(# C: @Counter; N: @integerdo 3->C.up; C.down->N#)

Theextentof mini3 is obtainedby combiningthePROGRAMfragment-formin mini3 , origin ’betaenv’ andinclude ’counter’. In additionthebody ’coun-terbody’ in counter impliesthatthecounterBody fragmentis alsoincludedin theextent.Theresultingform looksasfollows:

{****** The basic BETA environment ******}(# ...

Counter:(# Up: (# n: @integer enter n do n+7->n #);

Down: (# n: @integer do n-5->n exit n #);Private: @(# V: @integer #)

#)do {Initialize for execution}

(# C: @Counter; N: @integerdo 3->C.up; C.down->N#);{Terminate execution}

#)

Page 278: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.2 SEPARATION OFINTERFACE AND IMPLEMENTATION 267

As statedearlier, thepatternsdefinedin LIB arevisible in mini3 throughtheuseof include. However, the counterbody is not visible from mini3 . Thismeansthatanevaluationlike:

C.private.V+1->C.private.V

is not possiblewithin mini3 . That is evenif theextentof mini3 includesthecounterbody fragment,it is not visiblewithin mini3 .

Thedomainof a fragmentF is thatpartof theextentof F which is visiblewithin F. Thedomainof F consistsof thefragment-formsin F, plusthedomainof theorigin of F plusthedomainof possibleincludedfragments.

Thedomainof mini3 takesthefollowing form:

{****** The basic BETA environment ******}(# ...

Counter:(# Up: (# n: @integer enter n <<SLOT Up:DoPart>> #);

Down: (# n: @integer<<SLOT Down:DoPart>>exit n#);Private: @ <<SLOT Private:ObjectDescriptor>>

#)do {Initialize for execution}

(# C: @Counter; N: @integerdo 3->C.up; C.down->N#);{Terminate execution}

#)

Thedomainof mini3 is constructedasfollows:

G Thedomainof mini3 consistsof thePROGRAMfragment-formin mini3 , thedomainof betaenv (its origin), plus thedomainof the includedfragmentcounter .

G Thedomainof betaenv is theform in Figure17.3.G Thedomainof thecounter fragmentconsistsof theform definingthepat-

tern Counter , plus the domainof betaenv . Note that the body part ofCounter doesnotcontributeto thedomain.

In Section17.6theconceptsof extentanddomainaredescribedfurther.

17.2 Separationof interface and implementation

Organizinga programasa collectionof fragments(modules)is oneway ofdealingwith thecomplexity of largeprograms.A largesystem,however, con-sistsof a largenumberof fragments.A fragmentmayusea numberof other

Page 279: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

268 MODULARIZATION

fragments(via origin, includeor body),andbeitself usedby anumberof otherfragments.The resultmay in fact be a fairly complicatedstructure.For thisreasonit isnecessaryto limit theinterconnectionsbetweenfragments.Further-more,knowledgeaboutthedetailsof a fragmentshouldbe limited wheneverpossible.

A fundamentaltechniquein thedesignof softwaresystemsis todistinguishbetweenthe interfaceand implementationof a module. The interfaceof amoduledescribesthe part of the modulewhich is visible from modulesthatuseit. This includesa descriptionof how to usethemoduleandis sometimescalledthe ‘outsideview’ of the module. The implementationof a moduleisthepartof themodulewhich is necessaryto realizeit on a computer. This issometimescalledthe‘inside’ view of themodule.

An importantissueis the notion of encapsulationor informationhiding.Encapsulationmeansthat accessto the implementationpart of a moduleisnot possiblefrom outsidethemodule,i.e. the implementationof a moduleishidden. This meansthat theusageof a modulecannotdependuponinternaldetailsof its implementation,andthusit is possibleto changetheimplemen-tationof amodulewithoutaffectingits usage.

Encapsulationand separationof interfaceand implementationmay alsosavecompilationtime. In theMjølnerBETA System,asin mostothersystems,fragments(modules)canbeseparatelycompiled.A changein animplementa-tion modulecanthenbemadewithout recompilationof the interfacemoduleandmodulesusing the interfacemodule. This canyield significantsavingsin compilationtime. On theotherhand,a changein aninterfacemoduleim-pliesthatall modulesusingit mustberecompiled.Thiscanbeextremelytimeconsuming,thereforewe recommendcarefullydesigningcritical interfacestoreducetheneedfor futurechanges.It is, however, not possibleto avoid suchchangessincetherequirementsfor aninterfaceusuallychangeover time.

Programmingtakesplaceatdifferentabstractionlevels.Theinterfacepartof amoduledescribesaview of objectsandpatternsmeaningfulat theabstrac-tion level wherethemoduleis used.Theimplementationlevel describeshowobjectsandpatternsat the interfacelevel arerealizedusingotherobjectsandpatterns.

To sumup, encapsulationandseparationof interfaceandimplementationhave thefollowing advantages:

G Theuserof amodulecanonly accessits interfaceandthuscannotmakeuseof implementationdetails.

G It is possibleto changetheimplementationwithoutaffectingtheusageof amodule.

G A changein animplementationmodulecanbemadewithout recompilationof theinterfacemoduleandmodulesusingtheinterfacemodule.

Page 280: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.2 SEPARATION OFINTERFACE AND IMPLEMENTATION 269

NAME ’textlib’origin ’betaenv’body ’ textlibbody’

LIB:attributesSpreadText:

{A blank is inserted between all chars in the text ’T’}(# T: @Textenter T<<SLOT SpreadText:DoPart> >exit T#);

BreakIntoLines:{’T’ refers to a Text which is to be split into a}{no. of lines. ’w’ is the width of the lines.}(# T: ˆText; w: @integerenter(T[],w)<<SLOT BreakIntoLines: DoPart>>#)

Figure17.4 Interfacefragmentof thesimpletext library.

Thefragmentlanguagesupportsencapsulationandseparationof interfaceandimplementation.Onefragmentdefinesthe interfacewhile othersdefinetheimplementation.

Figure17.4shows the textlib fragmentwhich definestheinterfaceof alibrary text manipulatingpatterns.The library consistsof two patterns,eachhaving aslotasits do-part.Thisslotshouldbefilled with a<DoPart> definingtheimplementationof thepattern.The textlibbody fragmentin Figure17.5is theimplementationpartof thelibrary.

The body ’ textlibbody’ part of textlib specifiesthat the fragmenttextlibbody is automaticallyincludedin any fragmentusing textlib . Afragmentusing textlib will not be able to accessattributesdescribedintextlibbody . In other words; the extent of textlib includes textliband textlibbody , whereas the domain of textlib does not includetextlibbody . Figure17.6 shows a program fragmentwhich makesuseoftextlib .

Page 281: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

270 MODULARIZATION

NAME ’textlibbody’origin ’ textlib’

SpreadText: DoPartdo (# L: @integer

do (for i: (T.length->L)-1 repeat(’ ’,L-i+1)->T.Insert Ch

for)#)

BreakIntoLines:DoPartdo T.scan

(# sepInx,i,l: @integer;do i+1->i; l+1->l;

(if (ch<=’ ’ )// true then i->sepInx if);(if l//w then

(nl,sepInx)->T.InxP ut;i-sepInx->l

if)#);T.newline;

Figure17.5 Implementationfragmentof thesimpletext library.

NAME ’libuser2’origin ’betaenv’include ’ textlib’

program:ObjectDescriptor(# T: @Text;do ’Here I am!’->SpreadText-> Put Lin e;

’Once upon a time in the west ’->T;’a man came riding from east’->T.putText;(T[],10)->BreakInt oLi nes ;T->putText;

#)

Figure 17.6 Thefragmentlibuser2 includestextlib .

Page 282: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.2 SEPARATION OFINTERFACE AND IMPLEMENTATION 271

NAME ’stack’origin ’betaenv’body ’arraystack’

LIB: AttributesStack:

(# Private: @ <<SLOT private: ObjectDescriptor>>;Push: (# e: ˆText enter e[] <<SLOT Push: DoPart>> #);Pop: (# e: ˆText <<SLOT Pop: DoPart>> exit e[] #);New: (# <<SLOT New: DoPart>> #);isEmpty:

(# Result: @boolean<<SLOT isEmpty: DoPart>>exit Result#)

#)

Figure 17.7 Theinterfacepartof theStack pattern.

17.2.1 Abstract data types

One of the fundamentalconceptsin programdevelopmentis the notion ofabstract data type. In the context of BETA, an abstractdatatype is a classpatternwhoseinstancesarecompletelycharacterizedby a setof (procedure)patternattributes– sometimesreferredto asits ‘operations.’ Theseoperationsconstitutethe outsideview of the objects,whereasreferenceattributesanddetailsof thepatternattributesbelongto theinsideview (theimplementation).

The fragmentsin Figures17.7 and17.8 show an exampleof an abstractdatatypein BETA. Thefragmentsdefinetheinterfaceandimplementationofastackof text references.A stackis completelycharacterizedby its operationsPush , Pop, NewandisEmpty . Thestack maybeusedasshown in Figure17.9

Sincethedomainof stack doesnot includeits implementation,thestackcanonly beusedby meansof its operations.It is goodpracticeto definemostclasspatternsas‘abstractdatatypes,’ i.e. restricttheir interfaceto bepatternoperations.In somelanguages(e.g.Smalltalk),classpatternsarealwaysab-stractdatatypes.

Page 283: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

272 MODULARIZATION

NAME ’arraystack’origin ’stack’

private:ObjectDescriptor(# A: [100] ˆText; Top : @integer#)

Push:DoPartdo private.top+1->pri va te. top ;

e[]->private.A[pri va te. top ][]

Pop:DoPartdo private.A[private. to p][ ]-> e[] ;

private.top-1->pri va te. top

new: DoPartdo 0->private.top

isEmpty:DoPartdo (0 = private.Top)->resu lt

Figure17.8 Theimplementationpartof Stack .

Page 284: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.2 SEPARATION OFINTERFACE AND IMPLEMENTATION 273

NAME ’libuser3’origin ’betaenv’include ’stack’

program:ObjectDescriptor

(# T: @Text; S: @Stackdo ’To be or not to be’->T; T.reset;

Get:cycle(# T1: ˆTextdo &Text[]->T1[]; T.getText-> T1;

(if T1.empty // True then leave Get if);T1[]->S.push

#);Print:

cycle(# T1: ˆTextdo (if S.isEmpty // true then leave Print if);

S.pop->T1[];T1->putText; ’ ’->put

#)#)

Figure17.9 A fragmentusingthestackinterface.

Page 285: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

274 MODULARIZATION

NAME ’listStack’origin ’stack’

private:ObjectDescriptor(# head: ˆelm; elm: (# T:ˆText; next: ˆelm #)#)

Push:DoPartdo (# R: ˆprivate.elm

do &private.elm[]->R []; private.head[]->R. nex t[] ;e[]->R.T[]; R[]->private.head[] ;

#)

Pop:DoPartdo private.head.T[]- >e[ ];

private.head.next []- >pr iva te .he ad[ ];

new: DoPartdo NONE->private.hea d[]

isEmpty:DoPartdo (NONE=private.hea d[] )-> res ul t ;

Figure17.10 List implementationof stack.

17.3 Alter native implementations

It is possibleto have several implementationsof a giveninterfacemodule.Ingeneral,this meansthatdifferentfragmentsmaydefinedifferentbindingsforslotsin a givenfragment.

Supposethatwe want to defineanalternateimplementationof thestackfrom the previous section. In the alternateimplementationstackobjectsarerepresentedasa linkedlist. Thelist implementationis shown in Figure17.10.

We have to remove thebodyspecificationof thestack fragment,sinceitforcesthe arrayStack to alwaysbe includedaspartof theextentof stack .Instead,theuserof stack shouldhave a bodypartspecifyingtheappropriateimplementation.

Page 286: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.3 ALTERNATIVE IMPLEMENTATIONS 275

To sumup:

G Thestack musthaveno body:

NAME ’stack’origin ’betaenv’

LIB: AttributesStack:

(# ...#)

G A userof thestackmusthave a bodyselectinganimplementation.Thefollowing fragmentmakesuseof thelist implementation:

NAME ’libuser4’origin ’betaenv’include ’stack’body ’ listStack’

program:ObjectDescriptor

(# T: @Text; S: @Stackdo ...#)

G Thefollowing fragmentmakesuseof thearrayimplementation:

NAME ’libuser5’origin ’betaenv’include ’stack’body ’arrayStack’

program:ObjectDescriptor

(# T: @Text; S: @Stackdo ...#)

Page 287: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

276 MODULARIZATION

Sometimesit is not desirableto selectthe implementationof thestackat thepointwhereit is used.Considerafragmentusingthestack withoutspecifyinganimplementation:

NAME ’libuser6’origin ’betaenv’include ’stack’

program:ObjectDescriptor

(# T: @Text; S: @Stackdo ...#)

Thefragmentlibuser6 has,however, notbeencompletelyspecifiedsincethefreeslotsin stack have not beenbound.Thesimplestway of doingthis is tospecifya fragmentthatonly addsabodyspecification:

NAME ’libuser7’origin ’ libuser6’body ’arrayStack’

Thefragmentlibuser7 is acompleteprogram.

17.4 Program variants

Often, several variantsof a given programareneeded,usually if variantsofa given programhave to exist for several computers.The main part of theprogramis oftenthesamefor eachcomputer. For maintenancepurposes,it ishighly desirableto have only oneversionof thecommonpart. In theMjølnerBETA Systemprogram,variantsarehandledin the sameway asalternativeimplementationsof a module,i.e. differentvariantsof a modulebind someoftheslotsdifferently.

As anexample,assumethattwo variantsof aprogramareneeded.Assumethat they vary with respectto the implementationof the stack pattern. Thefragmentin Figure17.11is like the libuser6 fragmentabove, exceptthat ithasbeenextendedwith aslot. Thisslot is supposedto print informationaboutthe variant. The fragmentin Figure17.12is an exampleof a variantof thelibuser8 fragment.A similar variantmaybedefinedusingstackList .

Page 288: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.4 PROGRAM VARIANTS 277

NAME ’libuser8’origin ’betaenv’include ’stack’

program:ObjectDescriptor

(# T: @Text; S: @Stackdo ’Program Hamlet. ’-> PutText;

<<SLOT hamlet:ObjectDescr ipt or> >;’To be or not to be’->T; T.reset;

Get:cycle(# T1: ˆTextdo &Text[]->T1[]; T.getText-> T1;

(if T1.empty // True then leave Get if);T1[]->S.push

#);Print:

cycle(# T1: ˆTextdo (if S.isEmpty // true then leave Print if);

S.pop->T1[]; T1->putText; ’ ’->put#)

#)

Figure 17.11 The libuser8 fragment.

NAME ’libuser9’origin ’ libuser8’body ’ listStack’

hamlet:ObjectDescriptor

(#do ’Variant using list implementation of stack’->putLine;

#)

Figure 17.12 The libuser9 fragment.

Page 289: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

278 MODULARIZATION

NAME ’libuser10’origin ’betaenv’include ’mylib’include ’ textlib’

program:ObjectDescriptor

(# T: @Text;do Hello; World; newline;

’Here I am!’->SpreadText-> Put Lin e;’Once upon a time in the west ’->T;’a man came riding from east’->T.putText;(T[],10)->BreakInt oLi nes ;T->putText;

#)

Figure17.13 Exampleof a fragmentincludingtwo otherfragments.

17.5 Using several libraries

The examplesof librariesuntil now have only shown how to useonelibraryfrom a program.Thesyntacticcategory of a slot likeSLOT LIB:attributesdescribesa list of declarations.It is thuspossibleto bind anarbitrarynumberof LIB fragmentsto sucha slot. Figure17.13shows a fragmentthat includestwo libraries.

17.6 Visibility and binding rules

We now summarizethe rulesfor binding slots,andgive a precisedefinitionof theextentanddomainof a fragment.A generalskeletonof a fragmentisshown in Figure17.14.Theorigin Gis optional,andtheremaybezeroor moreincludes.Thecasem J 0 meansthat thereareno includes.Similarly, k J 0correspondsto a fragmentwith nobodies.

Theorigin-chainof F is a list of fragments:

G, G1, G2, ... Gn

whereG is theorigin of F, G1 is theorigin of G, etc. The fragmentGn hasnoorigin. Usually, Gn will bethebasicenvironmentbetaenv . Theorigin-chainmustbefinite withoutduplicates.

Thefragment-formsin F areboundby searchingfor freeslotsin theoriginchain,startingwith G.

Page 290: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.6 VISIBILITY AND BINDING RULES 279

NAME ’F’origin ’G’include ’A1’include ’A2’...include ’Am’body ’B1’body ’B2’...body ’Bk’

F1: S1ff1

F2: S2ff2

...

Fn: Snffn

Figure 17.14 A generalfragment.

The fragment-dependencygraph of F hasa nodefor eachfragmentre-ferredto via origin, includeandbody. The dependency graphis constructedasfollows:

(1) A directededgeis madefr om F to its origin.

(2) A directededgeis madefr om F to eachfragmentit includes.

(3) Constructthedependency graphfor eachbodyfragmentF.

(4) Steps1-3 arerepeatedfor eachfragmentreferredby origin, includeandbody.

The dependency graphmustbe acyclic, i.e. thereshouldbe no loops. Thismeansthat a fragmentcannotinclude itself directly or indirectly via otherfragments.Thedependency graphfor fragmentlibuser9 of Figure17.12isshown in Figure17.15

The extent of F is the extent of its origin, the extent of all fragmentsin-cluded,plustheextentof all bodies,andfinally F itself. Thismaybedescribedusingthe following equation,wherewe rely on the reader’s intuition for thedefinitionof theoperatorK :

Page 291: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

280 MODULARIZATION

betaenv

Stack

listStack

libuser8

libUser9

Figure 17.15 Dependency graphfor libuser9 .

Extent L F M J Extent L GMNKExtent L A1MNK Extent L A2MPO"O"OQK Extent L AmMRKExtent L B1MNK Extent L B2MPO"O"OQK Extent L BkMRKff1 K ff2 KSO"O#OTK ffn

Notetherecursivenatureof extent.Anything in theextentof theorigin is partof theextentof F, andsimilarly for includeandbody. The recursionis finitesincethe dependency graphis acyclic. Eventually, therewill be a fragmentwithout anorigin andfragmentswithout includeandbodyparts.

The domainof F hasa similar recursive definition. The domainof F in-cludesthe domainof the origin, the domainof all includedfragmentsandthefragmentitself. Thebodyfragmentsarenot includedin thedomain.Thefollowing equationdescribesthedomain:

Domain L F M J Domain L GMUKDomain L A1MRK Domain L A2MPO#O"OQK Domain L AmMK ff1 K ff2 KVO#O"OQK ffn

17.7 Exercises

(1) Define an interface fragmentand an implementationfragmentfor theRegister patternin Chapter9.

Page 292: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

17.8 NOTES 281

(2) Develop an alternative implementationfor the Register patternwheretheelementsarestoredin a linkedlist.

(3) Redothe soda-andvendingmachineExercise2 in Chapter7 andsplittheprograminto interface-andimplementationfragments.

(4) Redothe banksystemExercise3 in Chapter7 by splitting the programinto interface-andimplementationfragments.

17.8 Notes

Thegrammar-basedprincipleusedto definetheMjølnerBETA FragmentSys-temwasoriginally proposedby (Kristensenet al., 1983a).

Thehandlingof modularizationdiffersfrom languageto language.Somelanguages,like the original versionof Pascal,have no mechanismsfor sup-portingmodularization.Otherlanguageslike Modula2 andAda have modu-larizationconstructsaspartof the language.In theselanguagesthe interfaceof the datatypehasbeentextually separatedfrom the implementation.In CandC++ amodulecorrespondsto afile.

In (DeRemerandKrohn,1976) the term ‘programmingin the large’ wasintroducedto characterizetheconstructionof largeandcomplex systems.Themainpoint madeby DeRemerandKrohn is thatstructuringa largecollectionof modulesto form asystem(programmingin thelarge)is essentiallyadiffer-entactivity from thatof constructingtheindividualmodules(programminginthesmall). They proposetheuseof differentlanguagesfor thetwo activities:amoduleinterconnectionlanguageshouldbeusedfor describingthemodularstructure,anda conventionalprogramminglanguageshouldbe usedfor de-scribingthecontentsof modules.They alsoproposeamoduleinterconnectionlanguagecalledMIL 75. TheBETA FragmentSystemis anexampleof sucha moduleinterconnectionlanguage.

Page 293: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

282 MODULARIZATION

Page 294: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Chapter 18

ConceptualFramework

In Chapter2 a short introduction to the conceptualframework underlyingBETA was given. This chapterwill presenta more detaileddescriptionoftheframework. Wewill introduceconceptssuchasinformationprocessesandsystemsanddiscussabstraction,concepts,classificationandcomposition.Theframework providesa meansto beusedwhenmodelingphenomenaandcon-ceptsfrom the real world, it is thusa fundamentalbasisfor object-orientedanalysisanddesign.It is, however, alsoimportantfor implementation,sinceit providesa meansfor structuringandunderstandingtheobjectsandpatternsgeneratedby aprogramexecution.Theapproachpresentedin thisbookis thatanalysis,designandimplementationareprogrammingor modelingactivities,but at differentabstractionlevels.

Object-orientationis also being appliedto databases.This book is notaboutdatabases,but the framework andBETA languagepresentedherearealsorelevantfor object-orienteddatabases.Datamodelingis thesameactivityfor databasesandprogramming.Thereare,of course,additionalaspectsofdatabaseswhich arenot coveredby this book. In (Atkinsonet al., 1990) thefollowing is mentioned:persistenceof objects;secondarystoragemanage-ment;recoveryandqueryfacilities.

In therestof this chaptera numberof definitionsof variousconceptsaregiven.Thedefinitionsaregivenin English,andit is in mostcasesnotpossibleto givea precisedefinition.Thelevel of precisenessis intendedto belike thatof a dictionary. Most of theconceptsbeingdefinedareexamplesof so-called‘prototypical’ concepts(seebelow). The examplesfollowing the definitionsarethereforeof greatimportancefor understandingtheconcepts.Despitethedifficulties in makingprecisedefinitions,the experienceis that the conceptsintroducedareuseful,but that somepracticalexperienceis necessarybeforea satisfactoryunderstandingof theconceptscanbeobtained.This experiencemaybeobtainedby usingBETA in practicalsystemdevelopmentprojects.

283

Page 295: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

284 CONCEPTUAL FRAMEWORK

18.1 Physicalmodeling

The conceptualframework presentedhere reflectsa certain perspective onprogramming. It is deliberatelypresentedas one of many possibilities: inChapter2 otherperspectivessuchasproceduralprogramming,functionalpro-grammingand constraintprogrammingwere briefly mentioned. We defineperspectiveasfollows:

Definition 18.1 A perspective is themeansa personusesto structure her/histhinkingandunderstandingin relationto situationswithin somedomain.

Themeansdeterminethenatureof propertieswhich maybeconsideredim-portantfor a givensituation,andtherebyalsothenatureof propertiesthatareignored. Themeansalsoprovideconceptsandothermethodsof organizationto beusedin theinterpretationof theselectedandconsideredproperties.

For functional and constraintprogramming,the meansinclude mathemat-ics. For proceduralprogrammingthe meansinclude the conceptof a pro-grammablecalculator. In this chapter(someof) the meansof the object-orientedperspectivearepresented.

In Chapter2, theobject-orientedperspectiveonprogrammingwasdefinedasfollows:

Definition 18.2 A programexecutionis regardedas a physicalmodelsimu-lating thebehaviorof eithera real or imaginarypart of theworld.

Thekey word is ‘physical.’ The term‘physicalmodel’ is usedto distinguishthesemodelsfrom, for instance,mathematicalmodels. Part of reality mayoften bedescribedusingmathematicalequations:Newton’s Laws areanex-ampleof this. A physicalmodelis a modelconstructedfrom somephysicalmateriallike Lego bricks. Elementsof thephysicalmodelrepresentphenom-enafrom theapplicationdomain.Objectsarethecomputerizedmaterialusedto constructcomputerizedphysicalmodels.Objectsmaybeviewedasa kindof electronicLegobricks.

A collectionof thingswhich maybeusedto generatea setof phenomenamaybe calleda phenomenagenerator. If thephenomenageneratedarepro-cesses,thecollectionmaybecalleda processgenerator. Thesetof processesthatmightbegeneratedmaybecalledtheprocesssetof theprocessgenerator.

A collectionof Lego piecesis a phenomenagenerator. The phenomenageneratedwill usuallyberegardedasstatic,andabuilding setfor toy railroadsis a betterexampleof a processgenerator. With this very generaldescription,almostanything couldberegardedasa phenomenagenerator. In practicewewill of courseuseit in a muchmorerestrictedcontext – that of informaticsandof modelinganddesign.

A givenphenomena/processgeneratorputssomerestrictionsonwhichas-pectsof reality can be modeled. In addition, it definesthe possibilitiesfor

Page 296: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.1 PHYSICAL MODELING 285

obtaininga physicalsimilarity betweenreality and the model. Most ‘Legohouses’would probablyhave somecommonlyacceptedphysicallikenesstohousespeoplelive in. A toy modelof a railway shuntingyard may be usedfor seriousanalysisof aspectsof the real yard’s operation,andthe physicalsimilarity is obvious. The building setmay, however, alsobe usedto modelcarsmoving on a road,but with a questionablerealism,sincefor example,acarrepresentedby a toy locomotivewill notbeableto passanothercar, repre-sentedby anotherlocomotive,exceptatpredeterminedlocationson the‘road’andusingrulesthatdonot correspondto passingon realroads.

An analogcomputer, consistingof capacitors,resistanceandotherelectriccomponents,mayof coursebeusedto modeltheelectricbehavior of acertainclassof circuitry – theprocesssetof theanalogcomputer. But it may(andhas)alsobe usedsuccessfullyto model the managementof waterreservoirs in ahydroelectricpowersupplysystem.In this casethereis no physicalsimilaritybetweentherealityandthemodel.

The definition of object-orientedprogrammingimplies that all programexecutionsaremodelsof someotherexisting systems.For new systemsthisalsoholds,even thoughthe existing systemin that caseis a systemexistingin the mind(s)of the programmer(s).The distinctionbetweena real or animaginarypartof theworld needsfurtherelaboration.

Let usconsidermodelingpartsof therealworld. Examplesof thisaresim-ulationprograms– a programsimulatinga railway systemis clearlya modelof partof therealworld. Thetrains,stations,passengers,etc.,involvedin thesimulationmay all be representedasobjectsin the programexecution. Thefirst object-orientedlanguage,Simula,wasin fact inventedwith the purposeof simulation.

Considernext a library. A library consistsof books,cardfiles andfilesfor the registrationof loans. Eachof the files consistsof a numberof cardsdescribingbooksor loans. A computersystemhandlingthesefiles may beconsideredasaphysicalmodelof thelibrary (whichis arealpartof theworld).Thecardsin thefiles maynaturallyberepresentedby objectsin theprogramexecution,etc. This is an exampleof how to make a physicalmodel of amanuallyoperatedadministrativesystem.

The creationof computersystemsof courseincludesa greatdealof in-vention. Theseinventionsmaybeimaginedasnew phenomenaandconceptswith a well definedrole in theproblemdomain.They will thensubsequentlyberealizedasobjectsandpatternsin theprogramexecution. Oftenit is alsoa matterof tasteas to whetheror not an object is a representationof somereal world phenomenonor a new kind of phenomenon.Is a patientrecordarepresentationof apatientor anew kind of object?

Therearealsoexamplesof computerizedmodelswhereinitially thesystemwasconceivedof asa modelof someexisting partof theworld. However, astimegoeson,theEDP-systemcompletelyreplacestheoriginalmanualsystem

Page 297: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

286 CONCEPTUAL FRAMEWORK

problem specific concepts

abstraction

phenomena

Referent System

realized concepts

abstraction

objects

Model System

Modeling

ccc

Figure18.1 Modeling.

andbecomespartof reality itself. An exampleof this is acomputersystemfororganizingsecuritieslikestocksandbonds.Whenconstructingsuchasystemit is naturalto representthesecuritiesasobjectsandall thetradingwith secu-ritiesarethenreplicatedin theEDP-system.In somecountries,likeDenmark,theobjectsbecomethesecuritiesthemselves,i.e. the ‘real stocksandbonds’aretheobjectsandnot thepaperrepresentations.Eventually, peoplewill for-getaboutpaper-basedsecuritiesandonly think of object-basedsecurities.

Referent and model systems

Therealor imaginarypartof theworld beingmodeledwill in thefollowing becalledthereferentsystem, andtheprogramexecutionconstitutingthephysicalmodelwill becalledthemodelsystem.1 Figure18.1 illustratestheprogram-ming processasamodelingprocessbetweena referentandamodelsystem.

Theprogrammingprocessinvolvesidentificationof relevantconceptsandphenomenain the referentsystemand representationof theseconceptsandphenomenain themodelsystem.Thisprocessconsistsof threesub-processes:abstractionin thereferentsystem;abstractionin themodelsystem;andmod-eling. Pleasenotethatintentionallywedonot imposeany orderingamongthesub-processes.Abstractionin thereferentsystemis theprocesswherewe are

1Laterin this chapteradefinitionof thetermsystemwill begiven.

Page 298: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.2 INFORMATION PROCESSES 287

perceiving andstructuringknowledgeaboutphenomenaandconceptsin thereferentsystemwith particularemphasison theproblemdomainin question.We saythatwe arecreatingproblem-specificconceptsin thereferentsystem.Abstractionin themodelsystemis theprocesswherewe build structuresthatshouldsupportthemodelwe areintendingto createin thecomputer. We saythatwecreaterealizedconceptsin themodelsystem.Finally, modelingis theprocesswhereweconnecttheproblemspecificconceptsin thereferentsystemwith therealizedconceptsin themodelsystem.In themodelsystem,objectsandpropertiesof theseobjectsrepresentphenomenaandtheirpropertiesin thereferentsystem.

Theprogrammingprocessinvolvesidentificationof conceptsandphenom-enain thereferentsystemandtheir subsequentrepresentationin termsof ob-jectsandpatterns.Ultimately this is a questionabouthow to identify thepat-ternsandobjectsof ourprogramexecutions.It is notall aspectsof thereal(orimaginary)world thatcanbemodeledasa programexecution.We thereforehaveto identity thekind of phenomenathatwewantto modelasprogramexe-cutions.Thephysicalmodelsweareinterestedin arethosepartsof realitywewantto regardasinformationprocesses. In thenext sectionwe will introducethe notion of informationprocess,which will give us someguidelinesaboutidentifying objects.

Patternsaremeansfor representingconceptsof the referentsystem. To‘find thepatterns’it is thereforenecessaryto discusssubjectslike thenotionof conceptsand their relationsto phenomena,and importantaspectsof theabstractionprocess. Conceptsand abstractionwill be dealt with further inSection18.3.

18.2 Inf ormation processes

It is not all aspectsof reality that canbemodeledasprogramexecutions.Inthissectionwewill lookatthekindof phenomenawecanrepresentascomput-erizedmodels.Perhapsthemostimportantphenomenastudiedin informaticsareinformationprocesses.Programexecutionsareinformationprocesses,andinformationhandlingin offices,planningin corporations,etc., areotherex-amplesof suchprocesses.Theabovedefinitionof informaticsdoesnot implythatall phenomenato whichwemayassociateinformationaspects‘belong’ toinformatics.Informaticsrepresentsoneperspectivefor lookingatphenomena.Dataprocessingin apostofficemayberegardedasaninformationprocess,asaneconomicprocessor asa socialprocess,andthus‘belong’ to informatics,economicsor sociology, dependingupontheperspectivechosen.

An informationprocessis aspecialkind of process,andwedefineit in thefollowing way:

Definition 18.3 An informationprocessis a processwhere thequalitiescon-

Page 299: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

288 CONCEPTUAL FRAMEWORK

sideredare:

G Its substance, thephysicalmaterialthat it transforms.G Measurablepropertiesof its substance, the resultsof measurementrepre-

sentedbyvalues.G Transformationsof its substanceandthusits measurableproperties.

Thenotionof an informationprocessgivescertainguidelinesfor identifyingconceptsandphenomenain thereferentsystems.

Substance This is thephysicalmaterialthat is transformedby an informa-tion process.Phenomenalike ‘Socrates’,‘Mount Everest’,a medicalrecord,anda memorycell in a computerareall examplesof phenomenawhich havesubstance.Substanceis characterizedby a certainvolumeanda uniqueloca-tion in time andspace.A major aspectof substanceis identity. Two piecesof substancehave thesameidentity only if they arethesamesubstance.Theymay have identical properties: ‘Socrates’and ‘your teacher’may have thesameweight,ageandeyecolor, but they arenot thesameperson.

Measurablepropertiesof substance Substancehasno inherentpropertiesbesideshaving a certainvolumeanda uniquelocationin time andspace.Allotherpropertiesassociatedwith substancehave to be obtainedby measure-ments. A givenpropertyof somesubstancemaybe observedby performinga measurementresultingin a measureresult(measurement).A measurementmaybeasimplecountingof thenumberof petalsonafloweror it maybeper-formedusingadvancedequipment,suchasmeasuringradiationfrom a com-puterscreen.In general,a sequenceof actionsis involved in performingthemeasurement.

Weight, blood pressureandeye color of a personareexamplesof mea-surableproperties.Thestateof a memorycell of a computeris a measurableproperty.

The resultsof measurementsare usually describedby valuesto capturethemfor the purposeof comparingthem. This is so commonthat oneoftendoesnot distinguishbetweenmeasurementsandthe valuesdescribingthem.Thevalue‘82.5 kg’ maydescribetheweightof someperson.Thevalue‘82.5kg’ is actuallyan abstractionclassifyinga setof measurementson a weight.We may think of ‘82.5 kg’ asa conceptandthemeasurementsof theweightaspartof its extension.Becauseof this confusionvaluesareoftenconsideredthephenomenainsteadof theactualmeasurements.

Abstractionssuchasvalues,functionsandtypeshave beendevelopedtodescribemeasurablepropertiesof substance.

Page 300: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.2 INFORMATION PROCESSES 289

Transformations on substance An informationprocessis characterizedbytransformationswhich changeits substanceandtherebyits measurableprop-erties. Transformationsarepartially orderedsequencesof events. An eventchangesthe stateof the informationprocess,andeventsareorderedin time.Theorderingis partial. Theeventsaretheonly meansfor changingthemea-surablepropertiesof thesubstance.

Thefollowing phenomenaareexamplesof events:pushinga specificbut-ton at a specificpoint in time; ‘the birth of HansChristianAndersen’,and‘the transitionbetweenspringandsummer1984.’ Phenomenamay alsobesequencesof events like ‘Hannibal’s march acrossthe Alps’, ‘Columbus’America-expedition’ and‘eating.’

The notion of information processesgivescertainguidelinesfor the se-lection of phenomena.We have to considertangiblethingswherethe mainaspectis substance,we have to considermeasurablepropertiesof substance,andfinally, wehave to considerthetransformationson thesubstance.

Inf ormation systems

The definition of an informationprocessis very general,andin this sectionwewill putasystemperspectiveon informationprocesses.Thetermsystemisoften encounteredwithin informatics,andit hasbeenfrequentlyusedin thisbook.We defineasystemin thefollowing way:

Definition 18.4 A systemis a part of the world that a person (or group ofpersons)choosesto regard as a wholeconsistingof components, each com-ponentcharacterizedby propertiesandby actionsrelatedto thesepropertiesandthoseof othercomponents.

Accordingto thisdefinition,nopartof theworld ‘is asystem’asaninher-entproperty. It is asystemif wechooseasystemperspective.

In a systemperspective, substanceof information processesis orga-nized/perceivedin termsof components.The(measurableproperties)of sub-stancearethemeasurablepropertiesof components.The transformationsonthesubstanceareperceivedasactionsperformedby components.In thedef-inition of system,termslike ‘properties’ and ‘actions’ are used. Therearemany differentkinds of propertiesthat may be associatedwith components,andtherearemany waysof organizingactionswithin a system.Programex-ecutionsare information processes,and may be regardedas systemsin theabovesense.In thisbookwearemainly interestedin programexecutions,andthenotionof BETA programexecutionspresentedhereis onespecificway ofunderstandinganddescribingsystems.

Wearenow ableto giveamoreprecisedefinitionof programexecution:

Definition 18.5 A programexecutionis an informationprocessregardedasasystemdevelopingthroughtransformationsof its state.

Page 301: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

290 CONCEPTUAL FRAMEWORK

G Thesubstanceis organizedasobjects, which arecomputerizedmaterial.G A measurablepropertyof thesubstanceis a measurablepropertyof oneor

moreobjects.G Transformationsof stateare regardedaspartially orderedsequencesof ac-

tionsassociatedwith objects.G Conceptsare representedbypatternswhich areattributesof objects.

Thecomponentsof a programexecutionareobjects. Thepropertiesof com-ponents(objects)areattributes.A BETA programexecutioncanbemorepre-ciselydefinedasfollows:

Definition 18.6 ABETA programexecutionconsistsofacollectionof objects.Anobjectis characterizedbya setof attributesandanaction-part. Anattributemaybe: A referenceto anobject,a part-objector a pattern.

A BETA program executionhasthreekindsof objects: item, componentandsystem. Itemsmayhavetheir action-partexecutedbyotherobjects,com-ponentsmayexecutetheir action-partalternatelywith othercomponents,andsystemsmayexecutetheir action-partconcurrentlywith othersystems.

18.3 Conceptsand abstraction

Abstractionis probablythemostpowerful tool availableto thehumanintellectfor understandingcomplex phenomena.In the real world we areconfrontedwith a hugenumberof differentphenomenasuchasphysicalobjects,situa-tions, eventsandprocesses.All phenomenaaredifferent; thereareno twoidenticalpersons,two identicalcars,or two identicalflowers. It is, however,impossibleto dealwith all singlephenomenadirectlywithout toolsfor group-ing similar phenomena.Abstractionarisesfrom a recognitionof similaritiesbetweenphenomenaand conceptsand the decisionto concentrateon thesesimilaritiesandignorethedifferencesfor thetime being.Thesimilaritiesareconsideredasfundamentalandthedifferencesastrivial. An abstractioncoversa groupof phenomenacharacterizedby certainproperties.A word or pictureis usuallyintroducedto symbolizetheabstraction.An abstractionis alsore-ferredto asa concept.

18.3.1 Phenomenaand concepts

Until now we have beenrathervagueaboutthe termsphenomenonandcon-cept.Thefollowing definitionsgivemoreprecisedefinitionsof theseterms:

Definition 18.7 A phenomenonis a thing that hasdefinite, individual exis-tencein realityor in themind;anythingreal in itself

Page 302: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.3 CONCEPTSAND ABSTRACTION 291

Definition 18.8 A conceptis a generalizedideaof a collectionof phenomena,basedonknowledgeof commonpropertiesof instancesin thecollection

The following individuals are all examplesof phenomena: ‘WinstonChurchill’, ‘JohnF. Kennedy’and‘CharlesdeGaulle.’ They areall coveredbythegeneralconcept‘Person’,but alsoby themorespecializedconcept‘States-man.’ ‘Bounty’, ‘Jutlandia’ and ‘PederPars’2 are examplesof phenomenacoveredby theconcept‘Ship.’ ‘Mount Everest’,‘Mont Blanc’ areexamplesof phenomenacoveredby theconcept‘Mountain.’

The‘Statesman’conceptis anexampleof a roleplayedby persons.Otherexamplesof rolesare‘Employee’, ‘Owner’, ‘taxpayer’and‘Tenant.’

The above-mentionedphenomenaareexamplesof phenomenathat havesubstance.

Phenomenacanalsobeeventsthathappen.Thefollowing phenomenaareexamplesof events:pushinga specificbuttonat a specificpoint in time, and‘the birth of HansChristianAndersen.’ Phenomenamay alsobe sequencesof events like ‘Hannibal’s march acrossthe Alps.’ ‘Columbus’ America-expedition’ and‘making a specificpizza.’ For suchphenomenawe may de-velop conceptswherethe intensiondescribesthe sequencesof eventstakingplace.

We may also have phenomenathat recordevents. An exampleof sucha phenomenonis a ‘Flight record’ which may registercertaindataof a spe-cific flight, like SK911from Copenhagento LA on December12, 1989,etc.Anotherexampleis a ‘Systemcrash’whichmayberegisteredin a log book.

Measurablepropertiesof somematerialarealsoexamplesof phenomena.Examplesof theseincludethe ‘weight of a person’,the ‘blood pressureof aperson’and‘the temperaturein New York on December24,1984.’

Definition 18.9 A concept is traditionally characterizedby the followingterms:

G Theextensionof a conceptrefers to the collectionof phenomenathat theconceptsomehowcovers.

G The intensionof a conceptis a collectionof propertiesthat in somewaycharacterizethephenomenain theextensionof theconcept.

G The designationof a conceptis the collection of names(or pictures) bywhich theconceptis known.

The extension of the concept‘Person’ includes the phenomena‘WinstonChurchill’, ‘JohnF. Kennedy’and‘CharlesdeGaulle.’ Theintensionof ‘Per-son’ includesthe following properties: ‘able to think’, ‘walks upright’ and

2JutlandiaandPederParsarewell-known Danishships.

Page 303: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

292 CONCEPTUAL FRAMEWORK

‘usestools.’ In additionto ‘Person’thedesignationincludes‘HumanBeing’and‘Homosapiens.’

A phenomenonis a thing thathasdefinite,individual existencein realityor in the mind. The above examplesof phenomenaexist in reality. Exam-plesof phenomenaexisting in themind include‘SherlockHolmes’, ‘DonaldDuck’ and‘The Loch NessMonster’ (althoughsomepeoplethink it exists inreality!). Theextensionof conceptslike ‘Unicorn’, ‘Pixy’ and‘Nordic God’areexamplesof phenomenaexistingin themind. Thetermsconcretephenom-enaandabstractphenomenaareoftenusedto distinguishbetweenphenomenaexisting in realityor in themind.

Onephilosophicalissuehereis whetheror not it is useful to distinguishbetweenphenomenaandconcepts.Conceptsexist in themind andmaycon-sequentlybeviewedasabstractphenomena.Oneconsequenceof this is thatit is possibleto imaginea conceptwherethe extensionconsistsof concepts.This situationis usuallybetterdescribedby meansof generalization,as in-troducedbelow. In general,we think that it is usefulto distinguishbetweenconceptsandabstractphenomena.A conceptlike ‘Boat’ coversa collectionof phenomena,whereasan abstractphenomenonlike ‘Sherlock Holmes’ isoneindividual phenomenonexisting in themind of people.However, at thispoint it maybeappropriateto point out thatmostissuesin this chapterareofaphilosophicalnatureandthereforehighly subjective.

In theabovedefinitionof concepts,thepropertiesconstitutingtheintensionare thosethat ‘in someway’ characterizethe phenomenain the extension.Therearedifferentviews of conceptsthatgive differentinterpretationsto ‘insomeway.’ In thenext sectionswe look at two extremesin this respect.

18.3.2 Aristotelian view

The first of the two views hasits origin in the classicalAristotelian logic.Here conceptsare organizedin a logical hierarchicalconceptstructureandtheextensionof a conceptcontainsphenomenathatall satisfysomepreciselydefinedrequirements.This is expressedin the following characterizationoftheintension:

Definition 18.10 Theintensionof a conceptis a collectionof propertiesthatmaybedividedinto twogroups:thedefiningpropertiesthatall phenomenaintheextensionmusthaveandthecharacteristicpropertiesthat thephenomenamayor maynothave. Thenatureof thepropertiesis such that it is objectivelydeterminablewhetheror not a phenomenonhasa certainproperty.

The definingpropertiesdeterminea sharpborderbetweenmembersandnon-membersof a concept. Sinceit is objectively determinablewhetherornot a phenomenonhasa certainproperty, it is alsoobjectively determinable

Page 304: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.3 CONCEPTSAND ABSTRACTION 293

whetheror not a phenomenonbelongsto a givenconcept.In otherwords,theextensionof aconceptis uniquelydefinedby theintension.

TheAristotelianview of conceptshasturnedout to beusefulfor modelingsystematicand‘scientific’ conceptsasfoundwithin well establishedfieldslikemathematics,physics,zoologyandbotany.

For thepropertiesin the intensionit is importantthat it is objectively de-terminablewhetheror not a phenomenonhasa certainproperty. This resultsin a conceptstructurein which the conceptsarecharacterizedby sharpcon-ceptborders.In addition,the phenomenain the extensionof an Aristotelianconceptarerelatively homogeneous.This is in line with the‘scientific’ natureof theAristotelianview of concepts.

The propertiesof an Aristotelianconceptmay be describedby meansofpredicates,i.e. usingmathematics.Within scienceslike physicsandbiology,phenomenaareoftencharacterizedusingmeasurableproperties,asdescribedin Section18.2.Nomatterhow thepropertiesaredescribed,it is importantthatit is objectively decidablewhetheror not a given phenomenonhasa certainproperty.

18.3.3 Prototypical view

As alreadymentioned,theAristotelianview of conceptsis usefulfor model-ing systematicand‘scientific’ concepts,andit hasbeenusedfor many yearswith successespeciallywithin naturalsciences,althoughnot alwayswithoutproblems.

Therearea large numberof everydayconceptsthat cannotconvenientlybe describedasAristotelianconcepts.Examplesof suchconceptsare,‘rockmusic’, ‘intelligence’ and ‘food.’ Also, somemore technicalconceptssuchas‘object-orientedprogramming’and‘structuredprogramming’aredifficultto describeas Aristotelian concepts. It is commonlynot possibleto find acollectionof objectively decidablepropertiesthatdefinetheseconcepts,but itis possibleto find a collectionof propertiesthatmaycharacterizethesecon-cepts.However, oftenit is notpossibleto objectivelydeterminewhetheror notagivenphenomenonhasacertainproperty. Thishasledto thedevelopmentoftheso-calledprototypicalview of concepts(or fuzzyview or prototypetheory).In theprototypicalview theintensionis definedin thefollowing way:

Definition 18.11 Theintensionof a conceptconsistsof examplesof propertiesthat phenomenamayhave, togetherwith a collectionof typical phenomenacoveredby theconcept,calledprototypes.

The prototypical view differs from the Aristotelian view in a number ofways:

(1) It maynot beobjectively decidablewhetheror not a phenomenonhasapropertyof theintension.

Page 305: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

294 CONCEPTUAL FRAMEWORK

(2) The intensionis given by examplesof properties.All phenomenawillhave someof theproperties,but rarelyall. A phenomenonhaving someof thepropertiesmaynotbelongto theextensionof theconcept.

(3) Theprototypesaretypical phenomenabelongingto theextensionof theconcept.

Themajorconsequenceof this is that theextensionof a prototypicalconceptis notuniquelydeterminedby theintension.It requiresahumanjudgementtodecidewhetheror not a givenphenomenonbelongsto theconcept.Thephe-nomenain the extensionwill have variedtypicality andthe bordersbetweenconceptsareblurred.

The prototypical view of conceptsis more suited than the Aristotelianview to describemosteverydayconcepts.This is alsooftentruefor problem-specificconceptsof thereferentsystem.Below we discusstheconsequencesof this for thesystemdevelopmentprocess.

18.3.4 Other viewsof concepts

The Aristotelian andprototypicalview of conceptsrepresenttwo extremes,andit is possibleto imagineanumberof intermediateviews.

OnedifferencebetweenAristotelianandprototypicalviewsof conceptsiswhetheror not it is objectively decidableif a givenphenomenahasa certainpropertyor not.

Conceptual clustering Conceptualclustering is a variation of the Aris-totelianview. Theintensionmayhavepropertieswhichmaynotbeobjectivelydecided,thusit is basedonahumanjudgementwhetheror notaphenomenonis coveredby theconcept.

Prototypical conceptswith objective properties It is of coursepossibletoimagineprototypicalconceptswhereall thepropertiesareobjectively decid-able.

Defining versuscharacteristic properties Theintensionof anAristotelianconceptis divided into definingandcharacteristicproperties.In theory, eachof thesetwo setsof propertiesmaybeempty. It is easyto imagineAristotelianconceptswithout characteristicproperties.It is moreproblematicto imagineAristotelianconceptswithout definingproperties.Accordingto thedefinitionof an Aristotelianconcept,any phenomenonpossessingthe definingproper-tiesbelongsto theextensionof theconcept.Consequently, a conceptwithoutdefiningpropertieshasall phenomenain its extension.This is of courseuse-less.

Page 306: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.4 THE ABSTRACTION PROCESS 295

It is, however, still interestingto considera variantof Aristotelian con-ceptsthatallows thedefiningpropertiesto beempty. In this casethedefiningpropertiesaresupposedto be possessedby all phenomenain the extension,but not vice versa.It is thenamatterof humanjudgementto decideif a givenphenomenonbelongsto theconcept.

If propertiesareallowed to be non-objective, we arecloseto the proto-typical view of concepts.

18.3.5 Representingconceptsin BETA

A programminglanguagelike BETA is mainly usefulfor representingAris-totelianconcepts:a patternmaybeusedfor representinganAristoteliancon-cept. The instancesof thepatternrepresenttheextensionof theconcept,theobject-descriptorrepresentsthe intensionandthe nameof the patternrepre-sentsits designation.The intensionof a conceptis representedby meansofan object-descriptor, i.e. an object-descriptordeterminesthe kind of proper-ties that canbe represented.For an object-descriptorwe have attributesandactions. The attributesmay be part-objects,referencesto otherobjectsandpatterns.

18.4 The abstraction process

In boththereferentandthemodelsystems,conceptstructuresarecreated.Thisimpliesthatwehaveto discusstheprocessof producingandusingknowledge,i.e. issuesrelatedto the theoryof knowledgealsocalledepistemology. Theprocessof knowledgemaybesplit into threelevels:

(1) Thelevel of empiricalconcreteness.At this level we conceive reality orindividualphenomenaasthey are.Wedonot realizesimilaritiesbetweendifferentphenomena,nor do we obtainany systematicunderstandingofthe individual phenomena.We noticewhat happens,but neitherunder-standwhy it happensnor the relationsbetweenthe phenomena.In theprogrammingprocessthis correspondsto a level wherewe aretrying tounderstandthe singleobjectsthat constitutethe system. We have littleunderstandingof the relationsbetweenthe objects,e.g. how to grouptheminto classes.

(2) Thelevel of abstraction. To understandthe complicationsof the refer-entsystem,we have to analyzethephenomenaanddevelopconceptsforgraspingthe relevant propertiesof the phenomenathat we consider. Inthe programmingprocessthis correspondsto designingthe classesandtheirattributesandto organizingtheclassesinto a class/sub-classhierar-chy. At this level weobtainasimpleandsystematicunderstandingof thephenomenain thereferentsystem.

Page 307: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

296 CONCEPTUAL FRAMEWORK

(3) Thelevel of thoughtconcreteness.The understandingcorrespondingtotheabstractlevel is further developedto obtainan understandingof thetotality of the referentsystem. By having organizedthe phenomenaofthereferentsystemby meansof concepts,we maybeableto understandrelationsbetweenphenomenathatwe did not understandat the level ofempiricalconcreteness.We mayalsobeableto explain why thingshap-penandto predictwhatwill happen.

Theabove is an identificationof threelevelsappearingin theprocessof cre-ating andproducingknowledge. In this processthe perspective providesuswith variousmeansfor organizingandunderstandingourknowledge.Thefol-lowing arethreefundamentalmeansof organizationfor apprehendingtherealworld:

(1) Identificationof phenomenaand their properties. In perceiving the realworld peopleidentify phenomenaandtheir properties.Theresultof thisis a numberof singular phenomenacharacterizedby a selectedset ofproperties.Thephenomenaaresingularsincethey have not beenclassi-fied in termsof concepts.

Selectionof therelevantpropertiesof phenomenais highly domainspe-cific. In this book the domainis informationprocesses,asexplainedinSection18.2. Within informationprocessesthereis still a greatdealofvarietydependingon thekind of informationsystemto beconstructed.

(2) Classification.Classificationis themeansby which we form anddistin-guishbetweendifferentclassesof phenomena.Thatis weform concepts.Having identifiedphenomenaandtheirpropertiesandconcepts,wegroupsimilar phenomenaandconcepts.A classificationis often calleda tax-onomy. It is very commonto constructtaxonomiesto comparevarioussubjects.Whenclassificationis appliedrepeatedly, classificationhierar-chiesmaybeobtained.

(3) Composition. A phenomenonmay be understoodas a compositionofotherphenomena,i.e. thereis a distinction betweenwhole phenomenaandtheir componentphenomena.A car consistsof body, four wheels,motor, etc. A processof makinga pizzamay be understoodasa com-positionof severalsub-processes,including: makingthedough,makingthe tomatosauce,preparingthe topping, etc. Repeatedapplicationofcompositionleadsto compositionhierarchies.

In general,the processof creatingnew conceptscannotjust be explainedasconsistingof theabove sub-functions.In practice,thedefinition of conceptswill undergo drasticchanges.The understandingobtainedduring the devel-opmentprocesswill usually influenceprevious steps. It is, however, usefulto be awareof whethera problemis approachedtop-down or bottom-up. In

Page 308: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.5 CLASSIFICATION AND COMPOSITION 297

thesameway it is usefulto beawareof theabove-mentionedsub-functionsofabstraction.

In thenext sectionwe takeacloserlook at classificationandcomposition.

18.5 Classificationand composition

In reality we have to dealwith a hugenumberof conceptsandphenomena,andit would not bepossibleto dealwith thatamountof complexity withouttoolsfor hierarchical organizationof conceptsandphenomena.Classificationand compositionare meansto organizecomplexity in termsof hierarchies.The two termsareoften usedin two different,but complementary, ways. Insomesituationsthey areusedasadescriptionof sub-functionsgoingon in theprocessof producingknowledge. In this processwe constantlyapplyclassi-fication andcompositionto organizeour knowledge. In othersituationsthetwo termsareusedfor describing(static) relationsbetweenphenomenaandconceptsidentifiedduringtheprocessof identifying knowledge.

18.5.1 Classification

For classificationwedistinguishbetweentheclassificationof phenomenaandof concepts.In thefollowing wedefinetheterms‘clustering’and‘generaliza-tion.’ By classificationwethenmeaneitherclusteringor generalization:

Clustering Is a meansto focus on similarities betweena numberof phe-nomenaand to ignore their differences,i.e. clusteringis a classificationofphenomena.

Definition 18.12 To cluster is to form a conceptthat covers a collectionofsimilar phenomena.To exemplify is to identifya phenomenonin theextensionof a concept.Exemplificationis theinverseof clustering.

Clustering/exemplificationcorrespondsto the instance-ofrelationship.

Definition 18.13 Theinstance-ofrelationshipholdsbetweena conceptandaphenomenonin theextensionof theconcept.

Generalization Is a meansto focus on similarities betweena numberofconceptsandto ignoretheir differences,i.e. generalizationis classificationofconcepts.

Definition 18.14 To generalizeis to form a conceptthat covers a numberofmorespecialconceptsbasedonsimilaritiesof thespecialconcepts.Theinten-sionof thegeneral conceptis a collectionof propertiesthatareall part of the

Page 309: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

298 CONCEPTUAL FRAMEWORK

intensionof themore specialconcepts.Theextensionof thegeneral conceptcontainstheunionof theextensionsof themorespecialconcepts.

To specializeis to form a more specialconceptfroma general one. Spe-cializationis theinverseof generalization.

The termsgeneralization of andspecializationof are the namesfor thecorrespondingrelations.

Definition 18.15 A generalizationis a relationshipbetweena general conceptand a numberof more specialconcepts.A specializationis the inverseof ageneralization.

Theterm generalization is oftenusedabout the general conceptand thetermspecializationis oftenusedaboutoneof thespecialconcepts.

The concept‘Animal’ is a generalizationof the more specialconcepts‘Mammal’, ‘Fish’, ‘Bird’ and‘Reptile’, andall of thesemay in turn be con-sideredspecializationsof ‘Animal.’ The concept‘Mammal’ may be thoughtof asa generalizationof theconcepts‘Predator’and‘Rodent’,which maybeconsideredspecializationsof ‘Mammal.’

The concept‘Reservation’ may be considereda generalizationof ‘FlightReservation’, ‘TrainReservation’, ‘BoatReservation’ and‘Hotel Reservation.’

Theconcept‘Movement’maybeconsidereda generalizationof thecon-cepts‘Travel’, ‘Jump’ and‘Run.’

Classificationhierarchies

Classificationis oftenusedto definehierarchiesof conceptsandphenomena.An exampleof a classificationhierarchyfor animalsis shown in Figure2.2.This hierarchyis alsoanexampleof a generalization/specializationhierarchysinceit only includesconcepts.

The hierarchyin Figure 2.2 hasan importantproperty: it is tree struc-tured. Eachconcepthasat mostoneimmediategeneralization,implying thatthe extensionsof two conceptswith the sameimmediategeneralizationaredisjoint. The concepts‘Predator’and‘Rodent’ have thesamegeneralization‘Mammal’, and the extensionsof ‘Predator’and ‘Rodent’ aredisjoint. Thetreestructuredclassificationhierarchiesarean importantmechanismfor or-ganizingknowledge. They areappliedin many disciplinessuchasbiologyandchemistry. Thephenomenaof interestareclassifiedaccordingto selectedproperties.

Therearealsoexamplesof classificationhierarchiesthatarenot treestruc-tured.An exampleof suchahierarchyis givenin Figure18.2,3 whichshowsaclassificationof geometricfigures.This hierarchyis not treestructuredsince,for example,the concept‘Square’hastwo immediategeneralizations‘Rect-angle’and‘Rhombus.’

3Borrowedfrom (AbelsonandSussmann,1985).

Page 310: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.5 CLASSIFICATION AND COMPOSITION 299

polygon

quadrilateral

kitetrapezoid

triangle

isosceles triangle right triangle

equilateral triangle isosceles right triangle

parallelogram

rectangle rhombus

square

Figure 18.2 Classificationof geometricobjects.

It is often a desirablepropertyof a classificationhierarchythat it is treestructuredsincethis givesa simpler andmore systematicorganizationthanusingnon-treestructuredclassifications.In practice,however, oneoftenendsup with a classificationhierarchywhich is not treestructured.This may bethe caseif oneis classifyingthe samephenomenaaccordingto independentproperties. A non-treestructuredhierarchycan always be madetree struc-tured,which, however, oftengivesrise to clumsyhierarchies.Insteadof oneclassificationhierarchyonemay insteadmake two or moreclassificationsofthe samephenomena.This will thenresult in two or moreindependenttreestructuredclassificationhierarchies.

Consideranexamplewhereseveralrolesof peopleareof interest.It maythenbe of interestto classifypeopleaccordingto their profession,their na-tionality andtheir religion. This mayresultin threealternative treestructuredclassificationsof thesamephenomena.

Support for classificationin BETA

Classificationis supportedin BETA by meansof objectsandpatterns.Ob-jectsmaybeusedto representphenomenaandtheir properties.Patternsmaybe usedto representconcepts. Clearly, thereis supportfor the instance-ofrelationship.

Sub-patternsandvirtual patternssupportsgeneralization/specialization.In

Page 311: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

300 CONCEPTUAL FRAMEWORK

Chapters6–9numerousexamplesof modelingof generalization/specializationhierarchiesareshown.

It is obviousthat thesub-patternmechanismonly supportstreestructuredclassificationhierarchies.In addition,BETA doesnot supportthepossibilityof representingmorethanoneclassificationhierarchyof thesameobjects.InBETA it maythereforebenecessaryto representsuchclassificationhierarchiesby anothermechanism.

SomeprogramminglanguageslikeClos,C++andEiffel makeuseof mul-tiple inheritance. In thecaseswherethis is usedto representalternative clas-sifications,like theroleexampleabove, it mayleadto complicatedstructures.SeeSection6.8for a furtherdiscussionof multiple inheritance.

18.5.2 Composition

Compositionis ameansto organizephenomenaandconceptsin termsof com-ponentsof otherphenomenaandconcepts.Therearea numberof differentwaysof composingphenomenainto compoundphenomena.

A car may be viewed as consistingof a body, four wheels,etc. Thesecomponentsarephysicalpartsof thecar. A treemaybeviewedasconsistingof branches,a trunk, rootsandleaves.

A ‘Hotel Reservation’ may be viewed asa compositionof a ‘Person’,a‘Hotel’, a ‘Room’ anda ‘Date.’ It is, however, not meaningfulto view, forinstance,the personas a physicalpart of the hotel reservation. The corre-spondingcomponentis betterviewedasa referenceto aperson.

Wedefinecompositionin thefollowing way:

Definition 18.16 To composeis to form a compoundphenomenon/conceptby meansof a numberof componentphenomena/concepts.Propertiesinthe intension of the compoundphenomenon/conceptare describedusingthe componentphenomena/concepts.The extensionof the compoundphe-nomenon/conceptconsistsof phenomenawhich havecomponentsbelongingto theextensionof thecomponentphenomena/concepts.

To decomposeis to identify a componentphenomenon/conceptof a phe-nomenon/concept.Decompositionis theinverseof composition.

Compositiongivesriseto thecomponent-ofrelation:

Definition 18.17 The component-ofrelation is a relationship betweenaphenomenon/conceptandoneof its componentphenomena/concepts.

Thereareanumberof differentmeansfor makingcompositions.They mayallbedefinedasspecialcasesof compositionandcomponent-of.In thefollowingwe introducefour of thesemeans:whole-partcomposition;referencecompo-sition; localization;andconceptcomposition.They will only be introduced

Page 312: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.5 CLASSIFICATION AND COMPOSITION 301

asrelations,andno namefor thecorrespondingsub-functionof compositionwill begiven,althoughthis couldbedone.Thefour casesof compositionarenot independentin thesensethatthesamecomponentsmaybepartof two ormoreof the relations. The readermay find the distinctionbetweensomeoftheverbaldefinitionsbelow quitesubtle. However, hopefully the illustrationof therelationsin BETA will make thedistinctionclear.

Whole-part composition

One important form of compositionis the structuringof phenomenaintowholesandparts. A ‘Person’maynaturallybeviewedasconsistingof partslike ‘Head’, ‘Body’, ‘Arms’ and‘Legs.’ In turn, the‘Legs’ consistof ‘Lowerleg’, ‘Foot’, etc.

Definition 18.18 Thepart-ofrelationis a relationbetweena phenomenonandoneof its part phenomena.

A ‘Car’ maybeconsideredasconsistingof partslike ‘SteeringWheel’,‘Mo-tor’, ‘Body’ and‘Wheel’, i.e. ‘Wheel’ is apart-ofa‘Car’, a‘Motor’ is apart-ofa ‘Car’, etc.

Thefollowing exampleshowshow whole-partcompositionis supportedinBETA. Theexampledescribesa patternrepresentingtheconceptof a ‘Car’:

Car:(# aSteeringWheel: @SteeringWheel;

aMotor: @Motor;aBody: @Body;wheels: [4] @Wheel

#)

Thepart-ofrelationgivesriseto apart hierarchy.For moreexamplesof modelingwhole-parthierachiesin BETA, seeChap-

ter10.

Referencecomposition

A referenceis a componentof a phenomenonthat denotesanotherphe-nomenon.The ‘Person’componentof a ‘Reservation’ is actuallya referenceto a‘Person.’ Similarly, for the‘Hotel’ and‘Room’ components.Compositionof referencesgivesriseto thehas-ref-torelation:

Definition 18.19 The has-ref-torelation is a relationship betweena phe-nomenonand one of its components,being a reference to another phe-nomenon.

Page 313: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

302 CONCEPTUAL FRAMEWORK

The following examplesshows how referencecompositionis supportedinBETA. Theexampledescribestheconceptof a ‘Hotel Reservation’:

HotelReservation:(# aPerson: ˆPerson;

aHotel: ˆHotel;aRoom: ˆRoom;aDate: @Date

#)

The components‘aPerson’,‘aHotel’ and‘aRoom’ arereferencecomponentsof a ‘Hotel Reservation.’

Thecomponent‘aDate’ is representedasa part-object.It is, however, notintuitively usefulto modelthedateof ahotelreservationasa partobject.Thedateis a measurablepropertyof a hotelreservation. Modelingof measurablepropertiesis furtherdiscussedin Section18.7

For moreexamplesof modelingreferencecompositionin BETA, seeSec-tion 10.1.1.

Localization

Localizationis a meansfor describing/organizingthat the existenceof phe-nomena/conceptsarerestrictedto thecontext of a givenphenomenon,i.e. thelocalcomponentphenomena/conceptsaredependentuponthecompositephe-nomenon.The propertiesof a givenphenomenonmay be singularlydefinedphenomenaor conceptswhichonly haveameaningascomponentsof thecom-poundphenomenon/concept.

Definition 18.20 The is-local-to relation is a relationshipbetweena com-pound phenomenonand a locally defined dependentcomponent phe-nomenon/concept.

In Chapter8 a numberof examplesof localizationaregiven. Block structureis theBETA mechanismfor supportinglocalization.

Conceptcomposition

Conceptcompositionis a meansto definea compoundphenomenon/conceptby meansof a numberof independentcomponentconcepts.Conceptcompo-sition is thusa relationshipbetweena phenomenon/conceptanda numberofconcepts.Independencemeansthat thecomponentconceptshave a meaningindependentof thecompoundphenomenon/conceptbeingdefined.

Definition 18.21 A conceptcompositionis a relationshipbetweena com-poundphenomenon/conceptand a numberof independentcomponentcon-cepts.

Page 314: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.6 RELATIONS 303

A certainrelationshipbetweenthe concepts‘Person’, ‘Hotel’, ‘Room’ and‘Date’ maybeconsideredastheconceptcomposition‘Reservation.’ Thecon-cepts‘Person’,‘Hotel’, ‘Room’ and‘Date’ areindependent,sincethey haveameaningwithout theconceptof ‘Reservation.’ Note thata conceptlike ‘Re-servation’ maybeviewedasbothareferencecompositionandaconceptcom-position. In general,a conceptor phenomenamaybeviewedasoneor moreof thefour formsof composition.

Theconcept‘Travel’ maybeviewedasaconceptcompositionof conceptslike ‘Source’,‘Destination’,‘Duration’ and‘Subtravels.’

Theconcept‘Car’ maybethoughtof asaconceptcompositionof thecon-cepts:‘Horsepower’, ‘Body’, ‘Wheel’, ‘Motor’, etc.

18.6 Relations

Relationsareacommonform of abstractionusedfor organizingknowledge:

Definition 18.22 A relation is a union or connectionof phenomenaand/orconcepts

Someof theaboveabstractionmechanismsmayall beviewedasspecialkindsof relations. For classificationandcompositionwe have alreadyintroduceda numberof correspondingrelations,including instance-of,part-of, has-ref-to, etc. Theserelationsareexamplesof structural relations implied by theabstractionprinciples.In agivenproblemdomaintheremaybealargenumberof specialrelationsthatwemaybeinterestedin modeling.

Referencecompositionis actually a meansfor representingsimple bi-nary relationsbetweenphenomena.An exampleof sucha relation is ‘Em-ployeehas-aBoss’,which is a binary relationshipbetweenan employeeandhis or her boss. Otherexamplesare ‘Vehicle is-owned-byPerson’,‘Part is-manufactured-bySupplier’, ‘Hotel room is-reserved-by Person’and ‘Com-pany hasPresident.’ In Section10.1.1a numberof examplesof how to repre-sentrelationsin BETA areshown, including therelationshipbetweena bookandits author, andbetweenavehicleandits owner. In addition,thedifferencebetweenone-wayandtwo-wayrelationswasdiscussed.

Another importantaspectof relationsmetionedin Section10.1.1is thefunctionality of the relation. Considera relation ‘A R B’ meaningthat in-stancesof ‘A’ arein therelation‘R’ to instancesof ‘B.’ Relationshipsinvolvinginstancesof two classescanbeclassifiedinto thefollowing forms,dependingon thenumberof instancesinvolvedin eachinstanceof therelationship:

One-to-one: In eachinstanceof therelationship,at mostoneinstanceof ‘A’canbein relationto atmostone‘B.’

Page 315: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

304 CONCEPTUAL FRAMEWORK

One-to-many: In eachinstanceof the relationship,at mostoneinstanceof‘A’ canbein relationto many instancesof ‘B.’

Many-to-many: In eachinstanceof the relationship,many instancesof ‘A’canbein relationto many instancesof ‘B.’

For eachof the forms the phrase‘at mostone’ could be ‘exactly one.’ Thisis, for example,thecasewith a vehiclethatalwayshasanowner. Similarly,thephrase‘many’ canmeaneither‘ zeroor more’ or ‘oneor more’ or a fixednumber.

Section10.1.1alsomentionedthat it maybeusefulto representrelation-shipsasinstancesof patterns.This maybethecasefor relationsthatarenotbinaryor if additionalattributesareneededto characterizetherelation. ‘TheBeatles’,‘The Mills Brothers’,and ‘Simon andGarfunkel’ areexamplesofphenomenathatbelongto theextensionsof conceptssuchas‘Quartet’, ‘Trio’and‘Duo.’ As anexampleof a relationthat includesattributesotherthanjustdynamicreferences,the‘owner/owns’ relationfor vehicleswasgiven.

Theuseof relationsfor modelingphenomenaandconceptshavebeenusedextensively in the areaof databasesfor many years. The mostwidely usedmodel is the extendedentity-relationshipmodel, whereinformationis repre-sentedby meansof threeprimitiveconcepts:

(1) Entities, which representthephenomenabeingmodeled.

(2) Attributes, which representthepropertiesof thosephenomena.

(3) Relationships, which representtheassociationsamongphenomena.

TheextendedEERmodelfits well with object-orientedmodelingin thesensethatanEERmodelcanbedevelopedaspartof anobject-orientedmodel.TheEERentitiescorrespondto objects,andtheEERattributescorrespondto mea-surableproperties.Therelationshipsmayberepresentedassimplereferencesor aspatterns,asshown above.

18.7 Representativeelementsof a description

BETA may be usedasa tool for analysis,modelinganddesign. The BETAlanguageprovidessupportfor representingcertainpartsof reality. Thereare,however, variouspartsof reality thatcannotbedescribeddirectly in BETA. Itwill thereforebenecessaryto representsuchaspectsby meansof someotherBETA elements.

Let usfirst discussaspectsthatcanbedirectlyrepresentedin BETA. Theseinclude:

W Conceptscanberepresentedby patterns.

Page 316: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.7 REPRESENTATIVE ELEMENTSOF A DESCRIPTION 305

W Materialcanberepresentedby objects.W Classificationhierarchiescanberepresentedby sub-patternhierarchiesand

objects.W Compositionhierarchiescorrespondingto whole-partcomposition,refer-

encecomposition,localizationandconceptcompositioncanberepresented.W Relationscanberepresentedby referencecompositionor by relationalob-

jects.

Thebalance propertyof anAccount is anexampleof a propertythatcannotbe representeddirectly in BETA. In Chapter3, the balance propertyis rep-resentedasan integer part-object.Balance is anexampleof a measurableproperty, andthesubstanceof the integer part-objectdoesnotcorrespondtoa phenomenonin thereferentsystem.

Considernext the speedof a vehicle. This is an anotherexampleof apropertythatdoesnot havesubstance.It is, however, anobservableandmea-surableproperty, by for examplethecar’sspeedometeror thepoliceradar, andthemeasuringdevicesdohavesubstance.Themeasurementmapsanobserva-tion of thespeedon avaluespacewith km/hr (miles/hr)astheunit. Thereareanumberof alternativesfor representingameasurablepropertyin BETA. Thespeedattributemayberepresentedby anobjectasin:

Vehicle:(# Body: @(# ... #);

owner: ˆPerson;speed: @real

#)

Thereis, however, a greatdifferencebetweenthe descriptionof the speedpropertyandthe otherattributesof Vehicle . The real object representingspeeddoesnot correspondto a phenomenonin thereferentsystem.It is im-portantto be awareof which elementsof a BETA descriptioncorrespondtophenomena/conceptsin thereferentsystemandwhich do not. For this reasonwe introducethefollowing definition:

Definition 18.23 A representative elementof a BETA descriptionis a BETAelementcorrespondingto a phenomenonor conceptin the referent system.BETA elementswhich arenot representativearecallednon-representative.

In theabove descriptionof Vehicle , Body andowner maybeviewedasrep-resentativewhereasspeed is not.

Speedis anexampleof a measurableproperty, andto measurea propertya measurementmust be performed. The speedpropertycould thus be rep-resentedby a patternrepresentinga classificationof all measurementsof thespeed.Thisgivesusthethefollowing versionof Vehicle :

Page 317: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

306 CONCEPTUAL FRAMEWORK

NAME ’vehicle’origin ’betaenv’body ’vehiclebody’

LIB:AttributesVehicle:

(# Body @(# ... #)owner: ˆPerson;Speed: (# V: @real do <<SLOT Speed:DoPart>> exit V #)private: @<<SLOTprivate:ObjectDesc rip tor >>

#)

NAME ’vehiclebody’origin ’vehicle’

Speed:DoPartdo private.speed -> V

private:ObjectDescriptor(# speed: @real #)

Figure 18.3 Separationof the Vehicle descriptioninto representative andnon-representativeparts.

Vehicle:(# Body: @(# ... #);

owner: ˆPerson;Speed: (# V: @real do ... exit V #)

#)

The Speed patternis now intendedto performa measurementproducingthe‘speed’of thevehicle.How canwecompletethedescriptionof Speed?

Onepossibility is to have a privateReal object representingthe Speed .This may leave uscloseto thefirst alternative of representingSpeed directlyasa Real object. We may, however, separatetheactualrepresentationof thespeedfrom the Vehicle patternusing the fragmentsystem,asdescribedinChapter17. Figure18.3showshow adescriptionof Vehicle canbeseparatedinto representativeandnon-representativeparts.

Page 318: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.8 GRAPHICAL NOTATION 307

18.8 Graphical notation

Thesyntaxof theBETA languageusedin thisbookhasbeentextual. In Chap-ter 17 a diagrammaticnotationfor the fragmentlanguagehasbeenused. Itmayalsobepossibleto useadiagrammaticor graphicalnotationfor theBETAlanguage,especiallyuseful in analysisanddesign,sincea diagrammaticno-tation may provide a betteroverview of key objectsand patternsand theirrelations.In this bookcertaindiagramshave beenusedto illustratelanguageconcepts.

It is possibleto definean alternative graphicalsyntaxfor the BETA lan-guage,andoneproposalfor this wasgiven by (Bertelsenet al., 1986). Thisproposalgaveagraphicalsyntaxfor all languageconstructsin BETA. It is notobviousthatit is usefulto haveagraphicalnotationfor all languageelements,sinceperhapsnotall detailsarebestpresentedgraphically. TheMjølnerBETASystemincludesaneditorthatprovidesa diagrammaticnotationfor theover-all structureof aBETA description.Thesyntaxof thesediagramsis similar tothediagramsusedin this book.

Oneadvantageof a graphicalnotationis that it can illustratecertainse-manticrelationsmoredirectly thanthe textual representation.Oneexampleof this is classificationhierarchies,asshown in Figure6.1. Theclassificationstructureis definedassub-patterns,wherethenamesof super-patternsrefertothecorrespondingsuper-patterns.Usinga graphicalnotation,it is possibletoshow therelationshipbetweena patternandits sub-patternsmoredirectly byusing,for example,lines.

A graphicalnotationcan also be usedto show compositionhierarchies,specifiedrelations,active versuspassive objectsandcommunicationconnec-tionsbetweenobjects.

Graphicalnotationshavebeenusedfor many yearsto supportanalysisanddesign. This is especiallythe casefor methodsbasedon structuredanaly-sis/structureddesign. Recently, a numberof graphicaldesignnotationsforsupportingobject-orientedanalysisanddesignhaveappeared.

CASE tools

It may be impractical to usea graphicalnotationwithout the supportof acomputer-basedtool. A numberof so-calledCASEtools have beendevel-opedto supportthe variousdifferentdevelopmentmethods.In generalsuchtoolssupportconstructionandmanipulationof a graphicalnotationfor analy-sisand/ordesign.In addition,suchtoolsmaysupportthegenerationof codeskeletonsin someprogramminglanguage,which maythenbefilled in to pro-ducea final program. Theremay be a numberof problemswith suchtoolsdependingonthedifferencesbetweenthegraphicalnotationandtheprogram-ming language.Thefollowing problemshavebeenrecognized:

Page 319: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

308 CONCEPTUAL FRAMEWORK

(1) Theremaybelanguagemechanismsin thegraphicallanguagewhicharenot supportedby theprogramminglanguage.This maymake it difficultto recognizetheoriginal designin thecodeskeletons.

(2) Ideally, a CASEtool shouldmake it possibleto make a full specificationthat canbe usedto generatea completeexecutableprogram. With cur-rentspecificationlanguagesthis is notpractical,sinceit wouldbejust ascomplex aswriting theprogramdirectly. MostCASEtoolsthusgeneratea codeskeletonwhich mustbe completedto get a full implementation.Thedistancebetweenthe(graphical)specificationlanguageusedby theCASEtool andtheprogramminglanguageis referredto astheCASEgap.

(3) In theprocessof developingthecodeskeletonsinto completeprograms,it mayhappenthatit is necessaryto reorganizethecode.ThismeansthattheCASEdiagramswill have to beupdated,otherwisetherewill be in-consistenciesbetweenthediagramsandthecode.Theproblemof goingbackfrom thecodeto theCASEdiagramsis calledreverseengineering.

Theabove problemswith CASEtoolsaredueto the fact that theCASElan-guageandtheprogramminglanguagediffer. By usinganobject-orientedap-proachit is possibleto designaCASElanguageandaprogramminglanguagebasedon thesameabstractlanguage.Thegraphicalnotationbeingdevelopedfor BETA is just an alternative syntaxfor the sameunderlyingabstractlan-guage.Thegraphicalnotationandthetextualnotationaretwo alternativerep-resentationsof thesamelanguage.It is thereforepossibleto developa CASEtool/editor4 thatmakesit possibleto alternatebetweenusingthegraphicalno-tationandthetextual notation.It is easyto generatethetextual notationfromthegraphicalnotation,andviceversa.

Theproblemswith CASEtoolsaretypical for CASEtoolsbasedonstruc-turedanalysis/structureddesign.Thereasonis thatthereis amajorshift in lan-guagebetweenanalysis,designandimplementation.For CASEtoolsbasedonanobject-orientedapproachtheproblemis in generallessobvious. It is, how-ever, oftenthecasethattherearedifferencesbetweentheCASElanguageandtheprogramminglanguage.TheBETA approachis that thesameunderlying(abstract)languageshouldbe usedfor analysis,designandimplementation.Thiswill makeit easierto alternatebetweenanalysis,designandimplementa-tion.

18.9 Elementsof a method

In this sectionwe summarizesomeof the important tasksinvolved in anobject-orientedapproach.Note that this is not intendedto bea fully-fledged

4SuchaCASEtool/editoris currentlybeingdevelopedfor theMjølnerBETA System.

Page 320: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.9 ELEMENTSOFA METHOD 309

method,sincetherearemoreelementsof a methodthanpresentedhere.Ac-cording to (Andersenet al., 1986),a methodis characterizedby applicationarea,perspective(s)(e.g. language),andguidelines,i.e. techniques,toolsandprinciplesof organization.

The approachpresentedin this chapterconsistsof creatinga physicalmodel (called the model system)of part of reality (called the referentsys-tem). The systemdevelopmentprocess,which is the processof creatingamodelsystem,hastraditionallybeenorganizedinto analysis,designandim-plementation.The analysisphaseis primarily concernedwith understandingthe problemdomain;the designphaseis concernedwith constructionof thephysicalmodel; implementationis concernedwith realizingthis modelon acomputer.

Theconceptualframework presentedin theprevioussectionsmaybeap-plied to all threephases.Eachphaserepresentsthreedifferentdomains:thedomainof thereferentsystemis thephenomenaandconceptsof theapplica-tion domain;thedomainof themodelsystemis thephenomenaandconceptsof themodel,i.e. therepresentativeobjectsandpatterns;thedomainof theim-plementationaretheobjectsandpatternsusedto implementthemodel.Thus,onemain differencebetweenthe threephasesis the domain;anotheris thedegreeof formality, asweshallseebelow.

The separationof the systemdevelopmentprocessinto analysis,designand implementationis not a sequentialorganizationin the sensethat phaseoneis analysis,phasetwo is designandphasethreeis implementation.Oftenthesephasesarecompletelyintermixed,andit maybedifficult to distinguishbetweenthem.Many developersarenotevenawareof whetherthey aredoingoneor the other. In practiceit is very difficult to do analysiswithout doingsomedesign,andsimilarly doingdesignwithoutdoingsomeimplementation.Thesystemdevelopmentprocessis evolutionarywith respectto analysis,de-sign andimplementation.Oneimplication of this could be that it is perhapsnotusefulto distinguishbetweenanalysis,designandimplementation.Belowwe arguethatthis is in factuseful.

18.9.1 Generalapproach

The BETA languageandassociatedconceptualframework is to variousde-greesusefulfor analysis,designandimplementation.In this sectionwe sum-marizethe overall approachto all thesephases.In later sectionswe discusshow theapproachdiffersfor analysis,designandimplementation.

In thefollowing thedomaincanbethereferentsystem,themodelsystemor thecomputersystem.Within agivendomain,thefollowing stepsshouldbetaken.Again thestepsarenotsupposedto besequential,merelyachecklist:

(1) Select(relevant)phenomenaandconceptsfrom thedomainandselectthe(relevant)propertiesof thesephenomenaandconcepts.This includes:

Page 321: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

310 CONCEPTUAL FRAMEWORK

(a) Selectthematerial(objects)of thedomain.

Thesectionof relevantpropertiesof thematerialincludesselectionof:

(b) Measurableproperties.

(c) Possiblephysicalpartsof thematerial,i.e. whole-partcomposition.

(d) Possiblereferenceattributes,i.e. referencecomposition.

(e) Possiblelocal concepts:procedurepatterns,classpatterns,etc.,i.e.localization.

(f) Possiblenon-localconceptsusedfor describingproperties,i.e. con-ceptcomposition.

(g) Classificationof objectsaseitheractiveor passive.

For activeobjectsdescribetheaction-sequencesthey perform.Thisincludestheir participationinto concurrentaction sequenceswithotherobjects,andtheir involvementin alternatingactionsequences.

(2) Selectconcepts.Describeconceptsasprototypical,Aristotelian,etc.De-scribetheintensionof theconcepts.

(3) Selectrelationsbetweenphenomenaandconcepts.

It must be decidedwhethera relation is one-to-one,one-to-many ormany-to-many, andwhethera relationshouldberepresentedby apatternor just by meansof referenceattributes.

(4) Determineclassificationhierarchies,includingclusteringandgeneraliza-tion/specialization.It mustbeconsideredwhich of theclassificationhi-erarchiesaresingle/treestructuredandwhich aremultiple, andwhetherthereshouldbe several alternative classificationsof the samephenom-ena/concepts.

(5) Determinecompositionhierarchies.

The compositionhierarchiessuchaswhole-partcomposition,referencecomposition,localizationandconceptcompositionshouldbedetermined.

18.9.2 Analysis

Theanalysisphaseis primarily concernedwith understandingtheproblemdo-main,i.e. thereferentsystem.Thedomainreferredto in thegeneralapproachis thusthe referentsystem.We arethereforeconcernedwith theselectionofrelevantphenomenaandconceptsfrom thereferentsystem.

In this phaseit is importantthat thedeveloperis not restrictedto the(for-mal) mechanismof a programminglanguagelike BETA. This alsoappliestoany otherformal languageproposedfor analysisincludingthemany proposals

Page 322: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.9 ELEMENTSOFA METHOD 311

for a graphicalnotation. If the developeris restrictedto the useof a formalnotationthismayimposetoonarrow aview onthereferentsystem.Thedevel-opershouldmake useof any meansavailablewhendoinganalysis,includinginformal descriptions,graphicsand the conceptualframework presentedinthis chapter.

Prototypicalconceptsmay be useful for understandingthe problemdo-main. Problem-specificconceptsare often prototypical. BETA (and otherprogramminglanguages)is primarily suitedfor representingAristoteliancon-cepts.It is possibleto useapseudoformalnotationfor describingprototypicalconcepts.Suchadescriptionwill oftenincludeanEnglishdescription.

The realizedconceptsin the modelhave to be Aristotelian. Part of themodeling function is thus concernedwith giving prototypical conceptsanAristotelianinterpretation.This will often make the resultingcomputersys-temappearinflexible to theuser. It is importantthatthedeveloperis notforcedto useAristotelianconceptsat too early a stagein the developmentprocess.In addition,it is usefulto beawareof conceptsthatarebestdescribedaspro-totypical,but have beentransformedinto anAristotelianconcept.Of course,thedevelopershouldmakeuseof Aristotelianconceptswheneverpossible.

A major characteristicof analysisis that it may be necessaryto relax onthe formal notationprovided by the language.Examplesincludethe useofprototypicalconcepts,anddescribingalternative classificationsandmultipleinheritance.Thedevelopershouldhavetheability to extendthelanguageto atleastinformally describethedesiredaspectsof thereferentsystem.

18.9.3 Design

Thedesignphaseis concernedwith theconstructionof a physicalmodelthatcan be refinedinto an executableprogram. The domainreferredto in thegeneralapproachis thustheobjectsandpatternsof themodel.

The(possiblyinformal)descriptionsof phenomenaandconceptsidentifiedduring analysishave to be transformedinto formal descriptionsin termsofobjectsandpatterns,includinggiving Aristoteliandefinitionsof prototypicalconcepts.

As canbe seen,the programmingprocessis facedwith the problemthatnot only do we restricttherealismof our modelby only consideringa partoftheworld,but equallyimportant,themodelingprocesshasto takeinto accounttherestrictionsimposedby modelingapossibleprototypicalconceptstructurein thereferentsysteminto anAristotelianconceptstructurein themodelsys-tem. In general,theexpressivenessis limited by thelanguageusedto describethemodel.Otherexamplesof this includethesupportfor classificationhierar-chies:it maybenecessaryto transformmultipleclassificationhierarchiesintosinglehierarchies,or into theparticularinterpretationof multiple inheritancein theprogramminglanguage,just asit maybeawkwardto representseveral

Page 323: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

312 CONCEPTUAL FRAMEWORK

classifications.A largepartof designmaybeto inventnew thingsandconcepts.Remem-

berthatthemodelsystemis aphysicalmodelsimulatingthebehavior of eithera real or imaginarypart of theworld. The imaginarypart hasto be inventedduringdesign:thenew phenomenaandconceptsmusthave a meaningin thereferentsystem.

Theformalnotationcanbeaprogramminglanguageor agraphicaldesignlanguage.If BETA is useda mixture of graphicalandtextual syntaxcanbeused.In thedesignphaseit is importantto rememberthat thewholedescrip-tion/specificationmustberepresentativewith respectto thereferencesystem.A designdescriptionin BETA will thusbea fairly abstractprogram.

Designmay also involve the designof a userinterface. It is outsidethescopeof this book to discussthe designof userinterfaces. The generalap-proachof an object-orienteduserinterfaceis that representative elementsofthemodelshouldhave a representationon thescreen.Theusershouldhave afeelingof manipulatingthephysicalmodeldirectly. Of course,only selectedpartsof themodelmayberepresentedat any giventime, but theusershouldbeableto navigatein themodel.

Duringdesignit maybeusefulto constructscenariosand/orprototypesofthesystem.Thelatterwill involve implementation.

At somepoint during designit may be necessaryto make a requirementspecification,andin sucha specificationit shouldbe possibleto usepart ofthedesign.Selectedobjectsandtheir attributes,classpatterns,procedurepat-terns,etc., classificationhierarchiesand compositionhierarchiesshouldberelatively easyto presentfor theusers.Theform of thepresentationmaybeamixtureof diagrams,programtext andEnglishdescriptions,dependingonthebackgroundof theuser.

Page 324: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

18.10 EXERCISES 313

18.9.4 Implementation

Herethedomainof thegeneralapproachis thecomputersystem.Phenomenaandconceptsaretheobjectsandpatternsnecessaryto implementthedesign.In the implementationphasethe designdescriptionis refinedinto an imple-mentationthatcanbeexecuted.It is very importantto makeaclearseparationof representableandnon-representablepartsof thedescription.

18.10 Exercises

(1) Developasetof conceptsthatcapturewhatyouconsiderto betheessen-tial propertiesof a restaurant.

(a) Developageneralizationhierarchywith conceptsthataremoregen-eralthanRestaurantandconceptsthataremorespecialthanRestau-rant.

(b) Developacompositionhierarchy. Identifypossibleparts,referencesandconceptsof arestaurant.Identify possibleconcepts/phenomenawherea restaurantmaybeacomponent.

(c) Identify oneor morephenomenain theextensionsof theconcepts.

(d) Describetheintensionof thedevelopedconcepts.Describedefiningandcharacteristicpropertiesof theconcepts.

(e) Are thedevelopedconceptsAristotelianor prototypical?

(f) Identify substance,measurablepropertiesandtransformations.

(g) Try to modeltheprocessof servingacustomerin a restaurant.Thismay includeconceptslike ‘customer’, ‘table’, ‘waiter.’ It may in-cludeactionslike ‘get a table’, ‘get a menu’,‘order food’ and‘paythe bill.’ For eachobject in your model, identify which of its at-tributesaremeasurableproperties,partobjects,referencesto sepa-rateobjectsandlocal concepts.

(h) Include modelingof the restaurant’s food preparationprocessaswell.

(i) For which type of applicationsare the conceptsuseful? For cus-tomersusingrestaurants,for theownerof a restaurant,for thecityadministration,etc.?

18.11 Notes

Someauthorsusethe term paradigm insteadof perspective as usedin thisbook, i.e. termslike the object-orientedparadigmand functional paradigm

Page 325: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

314 CONCEPTUAL FRAMEWORK

are usedinsteadof object-orientedperspective and functional perspective.(NygaardandSørgaard,1987) argue that accordingto Kuhn, paradigmsaredefinedto dealwith majorshiftsin understandingwithin science,which is notthecasewith for examplethedifferencebetweenfunctionalprogrammingandobject-orientedprogramming. Object-orientedprogrammingand functionalprogrammingmayoftenbothbeusedin thesameprogram.

Variousauthorsusedifferent words for classificationand composition.Someof the terms like classificationand compositionand their more spe-cial variants– clustering,generalization/specialization,whole-partcomposi-tion, referencecomposition,localization,conceptcomposition– arewidelyaccepted,whereasothersarenot. Thetermclassificationis generallyacceptedalthoughsomeauthorsuseclassificationfor what hasbeencalledclusteringhere.Thetermgeneralization/specializationis widely accepted,with thesamemeaningashere.It is moreproblematicwith termsfor composition:thetermaggregation is oftenusedinsteadof composition.However, thereis no com-monlyagreeddefinitionof aggregation.Mostauthorsdefineaggregationto bewhole-partcomposition.Othersdefineit to belocalizationor conceptcompo-sition. In (SmithandSmith,1977a)aggregationseemsto bedefinedsimilarlyto conceptcomposition.

Relationshavebeenanimportantaspectof databases,analysisanddesignfor many years.Theentity-relationshipmodelwasintroducedin (Chen,1976).Relationshave not playeda centralrole within object-orientedprogramming,but are included in most books on object-orienteddatabasesand object-orientedanalysisand design(see(Hughes,1991; CoadandYourdon,1990;CoadandYourdon,1991;Booch,1991; Rumbaughet al., 1991), and(Wirfs-Brock et al., 1991)).

Theconceptualframework presentedherehasbeeninfluencedby similardevelopmentswithin artificial intelligenceanddatabases(SmithandSmith,1977a;SmithandSmith,1977b). The developmentof aconceptualframework has been an important part of the developmentofBETA. It doesnot seemto have playeda role in the developmentof otherobject-orientedlanguages.It is, however, of major importancein theareaofobject-orientedanalysis,modelinganddesign,aspresented,in for example,(Booch, 1991; CoadandYourdon,1990; CoadandYourdon,1991; Shlaerand Mellor, 1988; Rumbaughet al., 1991; Wirfs-Brock et al., 1991). TheBETA approachis, however, that analysis,designandprogrammingshouldnotbeconsideredasdifferentissues:it is all programmingatdifferentabstrac-tion levels.Theconceptualframework presentedhereis heavily influencedby(KnudsenandThomsen,1985). Theuseof characteristicpropertiesfor Aris-totelianconceptsis discussedin (FaberandKrukow, 1990). The processofknowledgeis from (Mathiassen,1981), but originatesfrom Karl Marx.

Object-orientedCASEfor BETA is discussedin (Sandvad,1990).

Page 326: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Appendix A

Grammar for BETA

Thisappendixdescribesagrammarfor theimplementedsubsetof BETA. Thegrammarformalismusedin theMjølnerBETA Systemis avariantof context-freegrammars.A structuredcontext-freegrammaris a context-freegrammar(CFG)wheretherules(productions)satisfya certainstructure.Eachnonter-minal mustbedefinedby exactlyoneof thefollowing rules:

1. An alternationrule hasthefollowing form:

<A0> ::| <A1> | <A2> | ... | <An>

where<A0>, <A1>, ...,<An> arenonterminalsymbols.Therulespecifiesthat<A0> derivesoneof <A1>, <A2>, ..., or <An>.

2. A constructorrule hasthefollowing form:

<A0> ::= w0 <t1:A1> w1 ... <tn:An> wn

where<A0>, <t1:A1> , ..., <tn:An> arenonterminalsymbolsandw0,w1, ..., wn arepossiblyemptystringsof terminalsymbols.This ruledescribesthat<A0> derivesthestring:

w0 <A1> w1 ... <An> wn

A nonterminalon theright sideof therule hastheform <t:A> wheretis a tag-nameandA is thesyntacticcategory. Tag-namesareusedto dis-tinguishbetweennonterminalsbelongingto thesamesyntacticcategory,consequentlyall tag-namesin arulemustbedifferent.If no tag-nameisprovidedthenthenameof thesyntacticcategory is usedasa tag-name.

3. A list rule hasoneof thefollowing forms:

<A> ::+ <B> w<A> ::* <B> w

315

Page 327: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

316 GRAMMAR FORBETA

where<B> is anonterminalandw is apossiblyemptystringof terminalsymbols.Thenonterminal<A> generatesa list of <B>sseparatedby ws:

<B> w <B> w ... w <B>

The +-rule specifiesthat at leastoneelementis generated;the * -rulespecifiesthatthelist maybeempty.

4. An optionalrule hasthefollowing form:

<A> ::? <B>

where<B> is a nonterminal. The nonterminal<A> may generatetheemptystringor <B>.

There are four predefined nonterminal symbols named <NameDecl> ,<NameAppl> , <String> and<Const> . Thesenonterminalsarecalled lexem-symbols, andthey derive identifiers,character-stringsandintegerconstants.Alexem-symbolmayalsohavea tag-namelike <Title:NameAppl> .

Thestartsymbolof thegrammaris <BetaForm> , which mayderiveeitheran<ObjectDescriptor> , an<Attributes> or a<DoPart> . Thesenontermi-nalsarethosethatcanbeusedto definefragment-forms/slots,cf. Chapter17.

The grammar

<BetaForm> ::| <DescriptorForm>| <AttributesForm>

<DescriptorForm> ::= <ObjectDescriptor><AttributesForm> ::= <Attributes><ObjectDescriptor> ::= <SuperPattenrOpt> <MainPart><MainPart> ::= (# <Attributes> <ActionPart> #)<Attributes> ::+ <AttributeDeclOpt> ;<SuperPattern> ::? <SuperPattern><SuperPattern> ::= <AttributeDenotati on><AttributeDeclOpt> ::? <AttributeDecl>

Page 328: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

GRAMMAR FORBETA 317

<AttributeDecl> ::| <PatternDecl>| <SimpleDecl>| <RepetitionDecl>| <VirtualDecl>| <BindingDecl>| <FinalBindingDecl >| <VariablePatternD ecl >

<PatternDecl> ::= <Names> : <ObjectDescriptor ><SimpleDecl> ::= <Names> : <referenceSpecific ati on><RepetitionDecl>:: = <Names> : [ <index> ] <referenceSpecifi cat ion ><VirtualDecl> ::= <Names> :< <ObjectSpecificatio n><BindingDecl> ::= <Names> :: < <ObjectSpecificat ion ><FinalBindingDecl> ::= <Names> :: <ObjectSpecification ><VariablePatternDe cl> ::= <Names> : ## <AttributeDenotat ion ><referenceSpecific ati on> ::| <StaticItem>

| <DynamicItem>| <StaticComponent>| <DynamicComponent>

<StaticItem> ::= @ <ObjectSpecificati on><DynamicItem> ::= ˆ <AttributeDenotat ion ><StaticComponent> ::= @ | <ObjectSpecificatio n><DynamicComponent> ::= ˆ | <AttributeDenotati on><ObjectSpecificati on> ::| <ObjectDescriptor>

| <AttributeDenotatio n><Index> ::| <SimpleIndex>

| <NamedIndex><NamedIndex> ::= <NameDcl> : <Evaluation><ActionPart> ::= <EnterPartOpt> <DoPartOpt> <ExitPartOpt><EnterPartOpt> ::? <EnterPart><DoPartOpt> ::? <DoPart><ExitPartOpt> ::? <ExitPart><EnterPart> ::= enter <Evaluation><DoPart> ::= do <Imperatives><ExitPart> ::= exit <Evaluation><Imperatives> ::+ <ImpOpt> ;<ImpOpt> ::? <Imp><Imp> ::| <LabelledImp>

| <LabelledCompoundIm p>| <ForImp>| <IfImp>| <LeaveImp>| <RestartImp>| <InnerImp>| <SuspendImp>| <Evaluation>

Page 329: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

318 GRAMMAR FORBETA

<LabelledImp> ::= <NameDcl> : <Imp><LabelledCompoundI mp> ::= ( <NameDcl> <Imperatives> <NameDcl> )<ForImp> ::= (for <Index> repeat <Imperatives> for)<IfImp> ::= (if <Evaluation> <Alternatives> <ElsePartOpt> if)<Alternatives> ::+ <Alternative><Alternative> ::= <Selections> then <Imperatives><Selections>::+ <Selection><Selection> ::| <CaseSelection><CaseSelection> ::= // <evaluation><ElsePartOpt> ::? <ElsePart><ElsePart> ::= else <Imperatives><LeaveImp> ::= leave <NameApl><RestartImp> ::= restart <NameApl><InnerImp> ::= inner <NameAplOpt><NameAplOpt> ::? <NameApl><SuspendImp> ::= suspend<Evaluations> ::+ <Evaluation> ,<Evaluation> ::| <Expression>

| <AssignmentEvaluat io n><AssignmentEvaluat ion > ::= <Evaluation> -> <Transaction><Transaction> ::| <ObjectEvaluation>

| <ComputedObjectEval uat ion >| <ObjectReference>| <EvalList>| <StructureReference >

<ObjectEvaluation> ::| <InsertedItem>| <reference>

<Reference> ::| <ObjectDenotation>| <DynamicObjectGener at ion >

<DynamicObjectGene rat ion > ::| <DynamicItemGenera tio n>| <DynamicComponentG enerat ion >

<InsertedItem> ::= <ObjectDescriptor><ObjectDenotation> ::= <AttributeDenotat ion ><ComputedObjectEva lua tio n> ::= <ObjectEvaluation > !<ObjectReference> ::= <Reference> []<StructureReferenc e> ::= <AttributeDenotati on> ##<EvalList> ::= ( <Evaluations> )<DynamicItemGenera tio n> ::= & <ObjectSpecificati on><DynamicComponentG enerat io n> ::= & | <ObjectSpecification ><AttributeDenotati on>::| <NameApl>

| <Remote>| <ComputedRemote>| <Indexed>| <ThisObject>

<Remote> ::= <AttributeDenotatio n> . <NameApl><ComputedRemote> ::= ( <Evaluations> ) . <NameApl>

Page 330: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

GRAMMAR FORBETA 319

<Indexed> ::= <AttributeDenotati on> [ <Evaluation> ]<ThisObject> ::= this ( <NameApl> )<Expression> ::| <RelationalExp> | <SimpleExp><RelationalExp>::| <EqExp> | <LtExp> | <LeExp>

| <GtExp> | <GeExp> | <NeExp><SimpleExp> ::| <AddExp> | <SignedTerm> | <Term><AddExp> ::| <PlusExp> | <MinusExp> | <OrExp><SignedTerm> ::| <unaryPlusExp> | <unaryMinusexp><Term> ::| <MulExp> | <Factor><MulExp> ::| <TimesExp> | <DivExp> | <ModExp> | <AndExp><EqExp> ::= <Operand1:SimpleExp> = <Operand2:SimpleExp ><LtExp> ::= <Operand1:SimpleExp> < <Operand2:SimpleExp ><LeExp> ::= <Operand1:SimpleExp> <= <Operand2:SimpleEx p><GtExp> ::= <Operand1:SimpleExp> > <Operand2:SimpleExp ><GeExp> ::= <Operand1:SimpleExp> >= <Operand2:SimpleEx p><NeExp> ::= <Operand1:SimpleExp> <> <Operand2:SimpleEx p><PlusExp> ::= <SimpleExp> + <Term><MinusExp> ::= <SimpleExp> - <Term><OrExp> ::= <SimpleExp> or <Term><unaryPlusExp> ::= + <Term><unaryMinusExp> ::= - <Term><TimesExp> ::= <Term> * <Factor><DivExp> ::= <Term> div <Factor><ModExp> ::= <Term> mod <Factor><AndExp> ::= <Term> and <Factor><Factor> ::| <TextConst>

| <IntegerConst>| <NotExp>| <NoneExp>| <RepetitionSlice>| <Transaction>

<RepetitionSlice> ::= <AttributeDenotati on>[ <Evaluation> : <Evaluation> ]

<notExp> ::= not <factor><noneExp> ::= none<Names> ::+ <NameDcl> ,<NameDcl> ::= <NameDecl><NameApl> ::= <NameAppl><SimpleEntry> ::? <TextConst><TextConst> ::= <String><IntegerConst> ::= <Const><SimpleIndex> ::= <Evaluation>

Page 331: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

320 GRAMMAR FORBETA

Page 332: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Appendix B

The Mjølner BETA System

The Mjølner BETA System1 is a programmingenvironment for object-orientedprogramming,which includesan implementationof BETA. Infor-mationabouttheMjølner BETA Systemis availablefrom:

Mjølner InformaticsA/SScienceParkAarhus, Phone: +457027 4343Gustav Wiedsvej 10, Fax: +457027 4344DK-8000AarhusC, E-mail: [email protected] Web: www.mjolner.com

A freeversionof theMjølner BETA Systemis availablefrom Mjølner Infor-maticsA/S eitherasaCD or downloadablefrom www.mjolner.com .

1Theoriginal printing of this bookcontainsa descriptionof theMjølner BETA Systemasof May 1993. The Mjølner BETA Systemhasundergoneextensive developmentsincethenandtheoriginalAppendixB is thereforeobsolete.

321

Page 333: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

322 THE MJŒLNERBETA SYSTEM

Page 334: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Bibliography

(AbelsonandSussmann,1985) G. Abelson, G.J. Sussmannwith J. Suss-mann.TheStructureandInterpretationof ComputerPrograms.Cam-bridgeMA: MIT Press,1985.

(Agesenet al., 1990) O. Agesen,S. Frølund, M.H. Olsen. Persistent andSharedObjectsin BETA. TechnicalReportIR-89, ComputerScienceDepartment,AarhusUniversity, 1990.

(Andersenet al., 1986) N. E. Andersen,F. Kensing,M. LassenJ.Lundin, L.Mathiassen,A. Munck-Madsen,P. Sørgaard.ProfessionalSystemDe-velopment.TekniskForlag,1986(in Danish).

(Atkinsonet al., 1990) M. Atkinson,F. Bancilhou,D.DeWitt, K. Dittrich, D.Maier, S. Zdonick. Object-OrientedDatabaseSystemManifesto.InDeductiveand Object-OrientedDatabases(W. Kim, J.M. Nicolas,eds.).Amsterdam:North-Holland,1990.

(Bertelsenet al., 1986) S. Bertelsen,S. Hvidbjerg, P. Sørensen.GraphicalProgrammingEnvironments– Applied to BETA. Masters thesis,ComputerScienceDepartment,AarhusUniversity, 1986.

(Blake andCook,1987) E. Blake, S. Cook.On IncludingPart HierarchiesinObject-OrientedLanguages,with anImplementationin Smalltalk.InProc.Euro. Conf. Object-OrientedProgramming, Paris,France,July,1987(Lecture Notesin ComputerScience, Vol 276, Berlin: Springer-Verlag).

(Bobrow andStefik,1983) D.G. Bobrow, M. Stefik. The LOOPSManual.Palo Alto CA: XeroxCorporation,1983.

(Booch,1986) G. Booch.Object-OrientedDevelopment.IEEE Trans.Soft-ware Engineering, 12(2), 1986.

(Booch,1991) G. Booch. Object-OrientedDesign with Applications. NewYork NY: Benjamin/Cummings,1991.

323

Page 335: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

324 BIBLIOGRAPHY

(BorningandIngalls,1981) A.H. Borning,D.H. Ingalls.A TypeDeclarationandInferenceSystemfor Smalltalk. Universityof Washington,1981.

(Brinch-Hansen,1975) P. Brinch-Hansen.TheProgrammingLanguageCon-currentPASCAL. IEEE Trans.Software Engineering, 1(2), 149-207,1975.

(Cannon,1982) H. Cannon. Flavors, A Non-Hierarchical Approach toObject-OrientedProgramming. Draft 1982.

(Chambers,1992) C. Chambers.Object-OrientedMulti-Methodsin Cecil. InProc. Euro. Conf. Object-OrientedProgramming, Utrecht, Nether-lands,June/July, 1992(Lecture Notesin ComputerScience, Vol 615,Berlin: Springer-Verlag).

(Chen,1976) P.P.SChen.TheEntity RelationshipModel: Towardsa UnifiedView of Data.ACM Trans.DatabaseSystems,1(1), 1976.

(CoadandYourdon,1990) P. Coad, E. Yourdon.Object-OrientedAnalysis.EnglewoodClif fs NY: Prentice-Hall/YourdonPress,1990.

(CoadandYourdon,1991) P. Coad,E.Yourdon.Object-OrientedDesign. En-glewoodClif fs NY: Prentice-Hall/YourdonPress,1991.

(Conway, 1963) M.E. Conway. Designof a SeparableTransition– DiagramCompiler. Comm.ACM, 6(7), 396-408,1963.

(Cook,1988) S.Cook.Impressionsof ECOOP’88.J. of Object-OrientedPro-gramming, 1(4), 1988.

(Cox,1984) B.R. Cox. Message/Object,An Evolutionary Change.IEEESOFTWARE,Jan.1984.

(Dahl andHoare,1972) Dahl O.-J., C.A.R Hoare. Hierarchical ProgramStructures.In Structured Programming (O-J. Dahl, E.W. Dijkstra,C.A.R.Hoare),AcademicPress,1972.

(Dahl et al., 1968) O.J.Dahl,B. Myrhaug,K. Nygaard.SIMULA67CommonBaseLanguage. NorwegianComputingCenter, Oslo,1968.

(Dahleet al., 1986) H.P. Dahle, M. Løfgren, O.L. Madsen,B. Magnusson.TheMjølner Project– A Highly EfficientProgrammingEnvironmentfor IndustrialUse.Mjølner reportno.1, Oslo,Malmø,Aarhus,Lund1986.

(DeRemerandKrohn,1976) F.L. DeRemer, H. Krohn. Programming-in-the-LargeversusProgramming-in-the-Small.IEEE Transactionson Soft-ware Engineering, 2(2), 80-86,1976.

Page 336: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

BIBLIOGRAPHY 325

(Dijkstra,1968) E. W. Dijkstra. Co-operatingSequentialProcesses.In Pro-grammingLanguages (F. Genuys,ed.), New York NY: AcademicPress,1968.

(ECOOP1987–1992)ECOOP, EuropeanConferenceon Object-OrientedProgramming.ConferenceProceedings1987-92.Lecture Notes inComputerScience, Berlin: Springer-Verlag,1987–1992.

(Eiffel, 1989) ”Interactive SoftwareEngineeringInc.. Eiffel: TheLanguage,Version2.2.SantaBarbara, CA,USA,1989.

(FaberandKrukow, 1990) L. Faber, L. Krukow. ThisTown is Big EnoughforMost of It – Modelling in OOP. Masters thesis,ComputerScienceDepartment,AarhusUniversity, 1990.

(Goldberg andRobson,1989) A. Goldberg, D. Robson.Smalltalk-80,TheLanguage and its Implementation. ReadingMA: Addison-Wesley,1989.

(Goodenough,1975) J.B. Goodenough.ExceptionHandling: Issuesand aProposedNotion.Comm.ACM, 18(12),436-49,1975.

(Griswold et al., 1981) R.E Griswold, D.R Hanson,J.T. Korb. GeneratorsinIcon. ACM Trans. on ProgrammingLanguages and Systems,3(2),144-61,1981.

(Grune,1977) D. Grune.A view of Coroutines.ACM SigplanNotices,75-81,July1977.

(Hanson,1981) HansonD.R.. Is Block StructureNecessary?.Software Prac-tice andExperience, 11, 853-66,1981.

(Henry, 1987) R. Henry. BSI Modula-2WorkingGroup:CoroutinesandPro-cesses.TheModusQuarterly, 8, 1987.

(Hoare,1972) C. A. R. Hoare.Proof of Correctnessof DataRepresentation.ActaInformatica,4, 271-281,1972.

(Hoare,1978) C.A.R Hoare.CommunicatingSequentialProcesses.Comm.ACM, 21(8), 666-677,1978.

(Hoare,1981) C.A.RHoare.TheEmperor’sold Clothes.Comm.ACM,24(2),75-83,1981.

(Holbæk-Hanssenet al., 1975) E. Holbæk-Hanssen,P. Handlykken, K. Ny-gaard.SystemDescriptionandtheDeltaLanguage. NorwegianCom-putingCenter, Publ.no523,1975.

Page 337: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

326 BIBLIOGRAPHY

(Holbæk-Hanssenetal., 1981) P. Handlykken,K. Nygaard.TheDELTA Sys-tem DescriptionLanguage:Motivation, Main Conceptsand Expe-riencefrom use.In Software EngineeringEnvironments(H. Hunke,ed.).Amsterdam:North-Holland,1981.

(Horowitz, 1983) E. Horowitz. Fundamentalsof ProgrammingLanguages.Berlin: Springer-Verlag1983.

(Hughes,1991) J.G.Hughes.Object-OrientedDatabases. Englewood Clif fsNJ: Prentice-Hall,1991.

(Jackson,1983) M. Jackson.SystemDevelopment. Englewood Clif fs NJ:Prentice-Hall,1983.

(JensenandWirth, 1975) K. Jensen,N. Wirth. PascalUser Manual and Re-port. Berlin: Springer-Verlag,1975.

(KahnandMacQueen,1977) G. Kahn, D. MacQueen.Coroutinesand Net-worksof ParallelProcesses.InformationProcessing77, B. Gilchrist(ed.),993-998.Amsterdam:North-Holland,1977.

(Keene,1989) S.E.Keene.Object-OrientedProgrammingin COMMON L ISP

– A Programmer’s Guide to CLOS. ReadingMA: Addison-Wesley1989.

(KernighanandRitchie,1978) B.W. Kernighan,D.M Ritchie. The C Pro-grammingLanguage 2nd edn.Englewood Clif fs NJ: Prentice-Hall,1988.

(Kim etal., 1987) W. Kim, J. Banerjee,H.-T. Chou, J.F. Garza,D.Woelk.CompositeObjectSupportin an Object-OrientedDatabaseSystem.In Proc.Object-OrientedProgramming, Languages,SystemsandAp-plications,Orlando,FL, 1987,(ACM SigplanNotices, 22(12)).

(Knudsen,1984) J. L. Knudsen.ExceptionHandling – A Static Approach.SoftwarePracticeandExperience, 429-49,May 1984.

(Knudsen,1987) J. L. Knudsen. Better-Exception Handling in Block-StructuredSystems.IEEE Software, 40-49,May 1987.

(KnudsenandThomsen,1985) J.Lindskov KnudsenandK. StougardThom-sen.A ConceptualFramework for ProgrammingLanguages. DAIMIPB-192,AarhusUniversity, April 1985.

(Knudsenetal., 1989) J.L. Knudsen, O.L. Madsen,C. Nørgaard,L.B. Pe-tersen,E. Sandvad.An Overview of theMjølner BETA System. Com-puterScienceDepartment,AarhusUniversity, Draft, Dec.1989.

Page 338: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

BIBLIOGRAPHY 327

(Knudsenet al., 1990) J.L. Knudsen, O.L. Madsen,C. Nørgaard,L.B. Pe-tersen,E. Sandvad. TeachingObject-OrientedProgrammingUsingBETA. In Proc.AppleEuropeanUniversityConsortiumAnnualConf.,Salamanca,1990.

(Knudsenet al., 1992) J.L. Knudsen,M. Løfgren,O.L. Madsen,B. Magnus-son (eds.).Object-OrientedEnvironments– TheMjølner Approach.EnglewoodClif fs NJ:Prentice-Hall,1993.

(Kristensenetal., 1976) B.B. Kristensen,O.L. Madsen,B. Møller-Pedersen,K. Nygaard.BETA ProjectWorkingNotes1-8. NorwegianComputingCenter, Oslo andComputerScienceDepartment,AarhusUniversity,Aarhus,1976–1982.

(Kristensenetal., 1983a) B.B. Kristensen,O.L Madsen,B. Møller-Pedersen,K. Nygaard.SyntaxDirectedProgramModularization.In Interacti-ve ComputingSystems(P. Degano,E. Sandewall, eds.).Amsterdam:North-Holland,1983.

(Kristensenetal., 1983b) B.B. Kristensen, O.L. Madsen, B. Møller-Peder-sen,K. Nygaard.AbstractionMechanismsin theBETA ProgrammingLanguage.In Proc.10thACM Symp.Principlesof ProgrammingLan-guages,AustinTX, January24-261983.

(Kristensenetal., 1985) B.B. Kristensen,O.L. Madsen,B. Møller Pedersen,K. Nygaard.MultisequentialExecution in the BETA ProgrammingLanguage.SigplanNotices,4(20),1985.

(Kristensenetal., 1987a) B.B. Kristensen, O.L. Madsen, B. Møller-Peder-sen,K. Nygaard.The BETA ProgrammingLanguage.In ResearchDirectionsin ObjectOrientedProgramming(B.D. Shriver, P.Wegner,eds.).Cambridge:MIT Press,1987.

(Kristensenetal., 1987b) B.B. Kristensen, O.L. Madsen, B. Møller-Pedersen,K. Nygaard.Classificationof Actions or Inheritancealsofor Methods.In Proc. Euro. Conf. Object-OrientedProgramming,Paris, France,June,1987 (Lecture Notesin ComputerScienceVol.276,Berlin: Springer-Verlag).

(Kristensenetal., 1988) B.B. Kristensen,O.L. Madsen,B. Møller-Pedersen,K. Nygaard.CoroutineSequencingin BETA. Hawaii InternationalConferenceonSystemSciences,21, January5-8,1988.

(KrogdahlandOlsen,1986) S. Krogdahl,K.A. Olsen.Modular andObject-OrientedProgramming.DataTid No. 9, Sept.1986(in Norwegian).

Page 339: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

328 BIBLIOGRAPHY

(Lampsonet al., 1977) LampsonB.W. et al.. Report on the ProgrammingLanguageEuclid.SIGPLANNotices,12(2), 1977.

(Leler, 1987) W. Leler. Constraint Programming– Their SpecificationandGeneration. ReadingMA: Addison-Wesley, 1987.

(LindstromandSoffa,1981) G.Lindstrom,M. L. Soffa.ReferencingandRe-tentionin Block-StructuredCoroutines.ACM Trans.onProgrammingLanguagesandSystems,3(3), 263-292,1981.

(Liskov andZilles, 1974) B. Liskov, S. Zilles. Programmingwith AbstractDataTypes.ACM SigplanNotices,9(4), 50-59,1974.

(Liskov et al., 1977) B. Liskov, A. Snyder, R. Atkinson, C. Schaffert. Ab-stractionMechanismsin CLU. Comm.ACM, 20(8), 564-576,1977.

(Madsen,1987) O.L. Madsen.Block Structureand Object Oriented Lan-guages.In: Research Directionsin Object Oriented Programming(B.D. Shriver, P. Wegner, eds.).CambridgeMA: MIT Press,1987.

(MadsenandMøller-Pedersen,1988b) O.L. Madsen, B. Møller-Pedersen.WhatObject-OrientedProgrammingmaybe— andwhat it doesnothaveto be.In Proc.Euro. Conf. Object-OrientedProgramming, Oslo,Norway, August,1988(Lecture Notesin ComputerScienceVol 322,Berlin: Springer-Verlag).

(MadsenandMøller-Pedersen,1989a) O.L. Madsen, B. Møller-Pedersen.Basic Principlesof the BETA ProgrammingLanguage.In Object-OrientedProgrammingSystems(G. Blair, D. Hutchinson,D. Shep-hard,eds.).London:PitmanPublishing,1989.

(MadsenandMøller-Pedersen,1989b) O.L. Madsen, B. Møller-Pedersen.Virtual Classes— A Powerful Mechanismin Object-OrientedPro-gramming.In Proc. Object-OrientedProgramming, Languages,Sys-temsand Applications,New Orleans,LS, 1989, (ACM SigplanNo-tices, 24(10)).

(MadsenandMøller-Pedersen,1992) O.L. MadsenB. Møller-Pedersen.PartObjectsandtheirLocation.TechnologyofObject-OrientedLanguagesandSystems— TOOLS7, Dortmund.EnglewoodClif fs NJ:Prentice-Hall 1992.

(Madsenet al., 1983) O.L. Madsen,B. Møller-Pedersen,K. Nygaard.FromSIMULA 67 to BETA. In Proc.11thSIMULA67 User’s Conf., Paris1983.NorwegianComputingCenter, 1983.

Page 340: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

BIBLIOGRAPHY 329

(Madsenet al., 1990) O.L. Madsen, B. Magnusson,B. Møller-Pedersen.Strong Typing of Object-OrientedLanguagesRevisited. In Proc.Object-OrientedProgramming, Languages, Systemsand Applica-tions,Ottawa,Canada,1990,(ACM SigplanNotices, 25(10)).

(Marlin, 1980) C.D. Marlin. Coroutines– A ProgrammingMethodology, aLanguageDesignandanImplementation.LectureNotesin ComputerScience, Vol 95.Berlin: Springer-Verlag,1980.

(Mathiassen,1981) L. Mathiassen.SystemsDevelopmentandSystemsDe-velopmentMethods(in Danish).Ph.D.thesis.Instituteof Informatics,OsloUniversity, 1981.

(Meyer, 1987a) B. Meyer. Genericity versusInheritance.In Proc. Object-OrientedProgramming, Languages,SystemsandApplications, Port-land,OR,1986,(ACM SigplanNotices, 21(11)).

(Meyer, 1987b) B. Meyer. Reusability:TheCasefor Object-OrientedDesign.IEEE Software, 2(4), March1987.

(Meyer, 1988) B. Meyer. Object-OrientedSoftwareConstruction. EnglewoodClif fs NJ:Prentice-Hall,1988.

(Møller-Pedersenetal., 1987) B. Møller-Pedersen,D. Belsnes,H.P. Dahle.RationaleandTutorial on OSDL: An Object-OrientedExtensionofSDL. ComputerNetworks& ISDNSystems,13, 97-117,1987.

(Naur, 1962) P. Naur (ed.). Revised Report on The Algorithmic LanguageALGOL 60.Regnecentralen.Copenhagen,1962.

(Nygaard,1986) K. Nygaard.Basic Conceptsin Object OrientedProgram-ming.ACM SigplanNotices,21(10),1986.

(NygaardandDahl,1981) K. Nygaard, O.-J. Dahl. Simula 67. In Historyof ProgrammingLanguages (R.W. Wexelblat, ed.). ReadingMA:Addison-Wesley, 1981.

(NygaardandSørgaard,1987) K. Nygaard, P. Sørgaard. The PerspectiveConceptin Informatics.In Computers and Democracy – A Scandi-navianChallenge (G. Bjerkness,P. Ehn,M. Kyng, eds.).Aldershot:Gower, 1987.

(OOPSLA1986–1992)OOPSLA, Object-OrientedProgrammingSystems,Languagesand Applications.ConferenceProceedings,1986–1992.ACM SigplanNotices.

Page 341: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

330 BIBLIOGRAPHY

(Raj andLevy, 1989) R.K. Raj,H.M. Levy. A compositionalModel for Soft-wareReuse.In Proc.Euro.Conf. Object-OrientedProgramming, Not-tingham, England,July, 1989 (BCS WorkshopSeries, Cambridge:CUP).

(ReesandClinger, 1986) J.ReesandW. Clinger(ed.).RevisedReporton theAlgorithmicLanguageScheme. MIT, TR no.174,August1986.

(Rumbaughet al., 1991) J.Rumgaugh,M. Blaha,W. Premerlani,F. Eddy, W.Lorensen.Object-OrientedModelingand Design. Englewood Clif fsNJ: Prentice-Hall,1991.

(Sakkinen,1989) M. Sakkinen.DisciplinedInheritance.In Proc.Euro. Conf.Object-OrientedProgramming, Nottingham, England, July, 1989(BCSWorkshopSeries,Cambridge:CUP).

(Sandvad,1990) E. Sandvad. Object-OrientedDevelopment– IntegratingAnalysis,DesignandImplementation. ComputerScienceDepartment,DAIMI PB-302,April 1990.

(ShlaerandMellor, 1988) S. Shlaer and S.J. Mellor. Object-OrientedSys-temsAnalysis– Modelingthe World in Data. Englewood Clif fs NJ:Prentice-Hall/YourdonPress,1988.

(ShriverandWegner, 1987) B. Shriver, P. Wegner(eds.).Research Directionsin Object-OrientedLanguages. Cambridge:MA: MIT Press,1987.

(Smith,1984) B. Smith.PersonalCommunication.Stanford 1984.

(SmithandSmith,1977a) J.M. SmithandD.C.P. Smith.DataBaseAbstrac-tions: Aggregation.Comm.ACM, 20(6), 396-404,1977.

(SmithandSmith,1977b) J.M. Smith and D.C.P. Smith. Data Base Ab-stractions: Aggregation and Generalization.ACM TransactionsonDatabaseSystems,2(2), 105-133,1977.

(StefikandBobrow, 1984) M. Stefik, D.G. Bobrow. Object-OrientedPro-gramming:ThemesandVariations.AI Magazine, 6(4), 40-62,1984.

(Stroustrup,1991) B. Stroustrup.TheC++ ProgrammingLanguage2ndedn.ReadingMA: Addison-Wesley, 1986.

(SwedishStandard,1987) SwedishStandard.Data Processing– Program-ming Languages– SIMULA. SwedishStandard SS63 61 14, ISBN91-7162-234-9,1987.

Page 342: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

BIBLIOGRAPHY 331

(Sørgaard,1988) P. Sørgaard.Object-OrientedProgrammingand Comput-erisedSharedMaterial. In Proc. Euro. Conf. Object-OrientedPro-gramming, Oslo,Norway, August,1988(Lecture Notesin ComputerScience, Vol 322,Berlin: Springer-Verlag).

(Tennent,1977) R.D.Tennent.LanguageDesignMethodsbasedonSemanticPrinciples.ActaInformatica,8(2), 97-112,1977.

(Tennent,1982) R.D.Tennent.TwoExamplesof BlockStructuring.Software-PracticeandExperience, 12, 385-392,1982.

(Thomsen,1987) K.S. Thomsen.Inheritanceon Processes,Exemplified onDistributedTerminationDetection.InternationalJournal of ParallelProgramming, 16(1), 17-52,1987.

(UngarandSmith,1987) D. Ungar, R.B. Smith. SELF: The Power of Sim-plicity. In Proc. Object-OrientedProgramming, Languages,SystemsandApplications,Orlando,FL, 1987,(ACM SigplanNotices, 22(12)).

(US Departmentof Defense,1980) Ada ReferenceManual . ProposedStan-dardDocument.UnitedStatesDepartmentof Defense,July1980.

(Vaucher, 1975) J. Vaucher. Prefixed Procedures:A StructuringConceptforOperations.Infor, 13(3), 1975.

(WangandDahl,1971) A. Wang, O.-J. Dahl. Coroutine Sequencingin aBlock StructuredEnvironment.BIT, 11, 425-449,1971.

(Wang,1982) A. Wang.CoroutineSequencingin Simula,Parts I-III . Norwe-gianComputingCenter, 1982.

(Wegner, 1983) P. Wegner. On theUnificationof DataandProgramAbstrac-tion in Ada. In Proc.10thACM Symp.on Principlesof ProgrammingLanguages,Austin,TX, 24-26January1983.

(Wegner, 1987) P. Wegner. Dimensionsof Object-BasedLanguage Design.Tech.ReportNo. CS-87-14,Brown University, 1987.

(Wikstrøm,1987) A. Wikstrøm. Functional ProgrammingUsing StandardML. EnglewoodClif fs NJ: Prentice-Hall,1987.

(Wirfs-Brock et al., 1991) R. Wirfs-Brock,B. Wilkerson,L. Wiener. Design-ing Object-OrientedSoftware. Englewood Clif fs NJ: Prentice-Hall,1990.

(Wirth, 1982) N. Wirth. Programmingin Modula-2. Berlin: Springer-Verlag,1982.

Page 343: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

332 BIBLIOGRAPHY

(Wulf andShaw, 1973) W.A. Wulf, M. Shaw. Global VariablesConsideredHarmful.SigplanNotices,8, 28-34,1973.

Page 344: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

Index

A-form, 257abstractdatatype,271abstractphenomena,292abstractsuper-patterns,85,191abstraction,286

in model/referentsystem,286accept,210action-part,30,290activecomponent,184activeobject,184activestack,184actualprocedure,163actualtype,163aggregation,314alternating,179alternation,178,225alternationrule,315anonymouspattern,113anonymousprocedure,92applicationof aname,72arithmeticoverflow, 239array, seerepetition,52assignment,68attached,184attribute-part,29attributes,290

basicpatterns,42restrictions,43,97

BETA programexecution,290binding,110

virtual pattern,110block structure,74,127,145boolean,42

CASEgap,308CASEtools,307

char, 42characteristicproperties,292class,39,41classpattern,39,41classification,145,296,297

hierarchies,296treestructured,298

classificationhierarchies,296classless,45clone,45,157cluster,297codepoint,180codesharing,125comment,27communicate,226communication,210component,75,179,183,290component-of,300compose,300composition,127,145,296

localization (block structure),302

reference,301whole-part,301

compositionhierarchies,296compoundsystems,201,215computedreference,67computedremotename,67concept,290,291conceptcomposition,302concretephenomena,292concurrency, 201,225constant,155constructionmode,74,75constructorrule,315controlpatterns,93

333

Page 345: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

334 INDEX

controlstructures,53coroutinesequencing,178

declaration,25virtual pattern,110

declarationof aname,72decompose,300default handler, 242definingproperties,292design,4designation,19,291deterministic,178deterministicalternation,178directqualification,113directsub-pattern,99directsuper-pattern,99do-part,29,53domain,267dynamiccomponentreference,184dynamicobject,34,75dynamicreference,32,180

encapsulation,268enter-part,29

for sub-pattern,95entrypattern,207evaluation,53,68evaluation-imperative,54,68exception,237,242

raisinganexception,242exceptionhandler, 242exceptionhandling,239

staticapproach,254exceptionoccurrence,237,242exceptionpropagation,245exemplify, 297exit-part,29

for sub-pattern,95explicit sequencing,197extend,49extendeddescriptor, 122extendedentity-relationshipmodel,

304extension,19,291

extent,262

final binding,122for-imperative,55fork-imperative,202form, 257formalprocedure,163formal type,163ForTo, 102fragment,256,260fragmentlanguage,256fragmentlibrary, 260fragmentname,260fragmentsystem,256fragment-dependency graph,279fragment-form,259fragment-group,259function,39functionpattern,39functionalstyle,170furtherbinding,122fuzzyview, 293

generalization,298generalize,297generalizedsemaphore,204generator, 179grammar-based,256

handler, 242has-ref-to,301hierarchicalorganization,297higherorderprocedure,163higherorderprocedurepattern,169

identificationof phenomena,296identity, 288if-imperative,56illusion of concurrency, 179imperative,27implementation,4, 268implementationmodules,255implicit sequencing,197in concurrency, 177in-line, 76

Page 346: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

INDEX 335

indivisible,205informationhiding,268informationprocess,287inheritance,102,144initial values,43inner, 90

shorthandnotation,94input parameters,29inserteditem,75insertedobject,75instancehandler, 243instance-of,297integer, 42intension,19,291–293interface,268interfacemodules,255is-local-to,302item,75,179,290

labeledimperative,58lazyevaluation,197leave-,58level

of abstraction,295of empiricalconcreteness,295of thoughtconcreteness,296

lexem-symbols,316list rule,315locality, 135localization,127,145locationof apartobject,153

main-part,98of a pattern,99of anobject,99of anobjectdescriptor, 99

many-to-many, 151,304measurableproperties,67,288measurement,68,288measurements,288modelsystem,286modeling,287module,163,255monitor, 201,206

multi-sequentialexecution,178multipleactionsequences,178multipleassignment,53multiple inheritance,300multiplepartobjects,149mutuallydependenttypes,166

new, 50no object,33nondeterminism,178,225nondeterministic,179nondeterministicalternation, 178,

225NONE,33

object,23pattern-defined,25,30singular, 24,30

objectkind, 74,75objectpattern,96object-descriptor, 23,28,30objects,290one-to-many, 151,304one-to-one,150,303optionalrule,316origin part,261origin-chain,278outputparameters,29

package,163packageobjects,165paradigm,313partcomponents,183parthierarchy, 301part-object,31,145,290part-of,301passeren,204pattern,30,290patternvariable,155pattern-definedobject,25,30persistent,6perspective,284phenomenagenerator, 284phenomenon,290

Page 347: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

336 INDEX

physicalmodel,2physicalstructure,6prefix,98prefix-pattern,98problem-specificconcepts,287procedure,39,40procedureinvocation,26,33procedurepattern,39,40process,193,297processgenerator, 284processof knowledge,295processset,284program,27programexecution,289programmingprocess,45properties,289PrototypeAbstractionRelationProb-

lem,136prototypetheory, 293prototype-based,45prototypes,293prototypicalview, 293pureobject-orientedstyle,170

qualification,35,121virtual pattern,110

qualified,35,100qualifiedreference,85qualifying pattern,35qualifying virtuals,124quasi-parallelsequencing,197

range,47readersandwriters,218real,42realworld apprehension,1realizedconcepts,287receiver, 211reference,290,300

assignment,32attribute,31,145composition,145equality, 58,65

referentsystem,286

relation,303oneway, 150one/two way, 303two way, 150

relationaloperators,43remoteaccess,35remote-name,24rendezvous,201repetition

extend,49new, 50range,47slice,50

representativeelement,305request,210restart-imperative,58restrictions,43,97resumed,185returnlink, 180reusability, 1, 255reverseengineering,308role,291run-timeerror, 33

scope,73scoperules,136Self,45,161self reference,39semaphore,201,203sender, 211sententialform, 257separatelycompiled,256sequentialexecution,178sequentialordering,177sharedobject,203sharedresource,203singularobject,24,25,30singularpart-object,31singularphenomena,296singularstaticobject,31slice,50slots,258smoothtermination,250

Page 348: OBJECT-ORIENTED PROGRAMMING IN THE BETA PROGRAMMING …jwalker/refs/betaBook.pdf · This is a book on object-orientedprogramming and the BETA programming language. Object-orientedprogramming

INDEX 337

specificationmodules,255specialrelations,303specialization,298specialize,298stabilityof design,1stateof aprogramexecution,27stateof anobject,27staticcomponentreferences,183staticcomponents,183staticobject,31,75staticreference,31streams,197structuralrelations,303structure,23,30structureobject,37structured context-free grammar,

315sub-pattern,83,98,99substance,288super-pattern,83,98,99suspended,184,185symmetriccoroutine,191synchronized,177synchronizedexecutionof objects,

209system,286,289,290systemperspective,289

taxonomy, 296this(P),39transformation,68,288transient,6type,39

value,68assignment,62equality, 58,65

variablereference,32variants,256virtual classpattern,139virtual pattern,105

binding,110continuedextension,114declaration,110

extension,110furtherbinding,122

virtual patternqualification,110virtual procedurepattern,106vrygeven,204

whole-partaction-sequences,146

whole-partcomposition,145