0% found this document useful (0 votes)
17 views

Lecture 16 Web Han

Object oriented systems

Uploaded by

Sekhamuri Ap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Lecture 16 Web Han

Object oriented systems

Uploaded by

Sekhamuri Ap
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.

6.001 Notes: Section 13.1


Slide 13.1.1
Inthislecture,wearegoingtolookatavery differentstyleof
creatinglargesystems,astylecalledobject oriented
programming.Thisstylefocusesonbreakingsystemsupina
differentmannerthanthosewehaveseenbefore.Tosetthe
stageforthis,wearefirstgoingtoreturntothenotionof
abstractions,andusethatideatoseehowwecancapture
objectswithsomeinternalstatethatreflectsthestatusofthose
objects.Wearegoingtobeledfromtheretoastyleof
programmingcalledmessage-passinginwhichwetreat
systemsasiftheyconsistoflargecollectionsofobjectsthat
communicatewithoneanothertocausecomputationtotake
place.
Slide 13.1.2
Let'sstartbygoingbackandthinkingaboutthetoolswehave
developedforthinkingaboutcomputation.Twoofthekeytools
wehavedevelopeddealtwithabstractions.
Wehaveseenprocedural abstractions.Heretheideaisto
captureacommonpatternofprocessingintoaprocedure,then
isolatethedetailsofthecomputationfromtheuseofthe
computation,bysimplynamingtheprocedureandusingthat
namewithappropriateconditionsontheprocedure'sinput.We
sawthatthisstyleofapproachisparticularlyusefulwhen
dealingwithproblemsthatareeasilyaddressedinafunctional
programmingapproach,thatis,wherewecantreatthe
proceduresasgeneralizedmathematicalfunctions,meaningthat
theiroutputforagiveninputwillbethesamewheneverweevaluateit.
Wehavealsoseendata abstractions.Heretheideaistomodularizeoursystembycreatingdatastructuresthat
capturekeypartsoftheinformationweneedtohandle.Thegoalistohidethedetailsoftherepresentationand
storageofthedatabehindstandardinterfaces,primarilyourconstructorsandselectors.Thismeanstheusercan
thenmanipulatedataobjectswithouthavingtoworryaboutdetailsofhowtheyaremaintained.
Asyoumightexpect,oftenthedataabstractionsandtheproceduralabstractionsworkhand-in-hand,withthe
proceduresusedtomanipulatethedatausingthedataabstractioninterfaces,andwiththestructureofthe
procedurestendingtomirrortheactualstructureofthedata.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.1.3
Thegoalineachcaseisactuallythesame:wewanttohide
detailsoftheabstractionsothatwecantreatcomplexthingsas
iftheyareprimitiveunits.Inthecaseofprocedural
abstractions,wewanttohidethedetailsofthecomputation,
andtreattheprocedureasaprimitivecomputationalunit.Inthe
caseofdataabstractions,wewanttohidethedetailsofhow
componentsaregluedtogether,andtreateachunitasan
abstractcollectionofparts.
Slide 13.1.4
Giventhatwewanttouseabstractionsasatoolincontrolling
complexityinlargesystems,thereareseveralquestionsthat
comeupwhenthinkingabouthowtouseabstractions.Thefirst
is:whatisthebestwaytobreakanewproblemareaupintoa
setofmodules?Bothdatamodulesandproceduremodules?As
wehavealreadyseeninearlierlectures,someproblemsbreak
upinmultipleways,andbreakingthemupindifferentways
makessomeprocesseseasierandothersharder.Soakey
questionis:HowdoIusetheideaofabstractiontobreak
systemsintomodulesandwhatsthebestwaytodothis?
Thesecondquestiondealswithhoweasyitistoextendthe
system.IfIwanttoaddnewdatatypestomysystem,isthat
easy?IfIwanttoaddnewmethodstomysystem,newwaysofmanipulatingdatatypes,isthateasy?Wehave
seenseveralexamplesofthisalready,wearenowgoingtoreturntothesequestionsinordertoleadtoavery
differentwayofbreakingsystemsupintoconvenientsizedchunks.
Slide 13.1.5
Let'sstartbygoingbacktodataobjectsanddataabstractions.
Hereisthetraditionalwayoflookingatdata,atleastaswe
havedonethingssofar.
First,webuildsomecomplexdatastructureoutofprimitives,
forexample,conscellsorpairs.Second,weusetagsto
identifythetypeofstructurebeingrepresented.Thistellsus
howtointerpretthedifferentslotsintheliststructure.For
example,isthecaroftheliststructurethenameofaperson
orhisbattingaverageorhisGPA?
Then,thedataabstractionisactuallybuiltbycreatingasetof
proceduresthatoperateonthedata.Theseareproceduresthat
takeininstancesofthedata,useselectorstogetoutthepieces,dosomemanipulationtocreatenewpieces,and
thenusetheconstructortore-gluetheabstractionbacktogether.Thisledtotheconceptofdata-directed
programming,whichwesawearlier.Weusethetagtodeterminetherightsetofprocedurestoapply.Andthis
allowstheusertoprograminagenericfashion.Theycanfocusonwhat theywanttodo,buthavethecodedirect
thedatatotherightplacefortheactualwork.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.1.6
Hereisasimpleexampletoillustratethispoint.SupposeIhave
asetofdifferentgeometricobjects,thingslikenumbers,lines,
shapes,andIwanttowriteaprocedure,oranoperation,that
willscaleeachofthoseobjectsbysomeamount.Thena
genericoperation,underthedata-directedapproachwouldlook
likethisprocedureshownhere.Givenanobjectandmydesired
scalefactor,Iusethetypeoftheobjecttodispatch:ifitisa
number,Ijustmultiply;ifitisaline,Ishipittotheprocedure
thatwillscalealine,andsoon.
ThepointofthisexampleisthatIthinkaboutthingsintermsof
thekindsofobjectsIhaveandproceduresformanipulating
eachdistinctobjecttype.Iusethetagorthetypeoftheobject
totellmewhichproceduretosendtheobjectto.
Slide 13.1.7
Sonowlet'sgobacktoourquestions.Howeasyisittoextend
suchasystem,asystemwherewearebreakingthingsupinto
taggeddata,andusingdatadirectedprogramming?First,ifwe
addanewdatatypetooursystem,whatdowehavetodo?
Wellwecanseefromourexamplethatwewillhavetoallthe
procedureslikescale,toaddanewclausetoeachcond,
dispatchingonthatnewtypeofobject.Asaconsequence,if
therearemanysuchprocedures,wehavealotofchangesto
make,bothagreatdealofcodetowrite,andmoreimportantly
makingsurethatwechangealltherelevantprocedures.
Ifweaddanewoperationormethod,whatdoweneedtodo?
Thisiseasier,aswejustneedtodevelopasubprocedureforeachtypeofobjecttowhichthemethodwillapply.
Thusinthisstyleofprogramming,addinganewdatatypeispainful,whileaddinganewmethodisreasonable.As
aconsequence,thisapproachtomodularizingsystemsworksbestwhenthereareonlyafewdataabstractionsor
whenthechangesaremostlynewmethodsoroperations,orwhenthedifferentkindsofdatastructuresinthe
systemaremostlyindependentofoneanother.Inthosecases,thisstyleofapproachworkswell.Butnoteverything
fitsthesecases.Whatshouldwedointhosecases?
Slide 13.1.8
Solet'sstepbackfromthisorganizationforasecond.Oneway
tothinkaboutstructuringalargesystemistorealizethatweare
likelytohavealargenumberofdifferentdataobjects(or
instancesofdataabstractions),andalargenumberof
operationswewanttoperformonthoseobjects.Conceptually,
thismeanswehaveabigtable,wherewecanuseadifferent
rowforeachoperationwewanttoperform,andadifferent
columnforeachkindofdataabstractionwehave.Thenateach
elementinthistable,wecanconceptualizehavingaspecific
procedure,intendedtoperformtheparticularoperation(e.g.
scaling)ontheparticularkindofdataobject(e.g.anumber).
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.1.9
Onewayofactuallybuildingsuchasystemistofocusonthe
rowsofthetable,thatistheoperations.Indeed,ouruseof
taggeddatawasbasedaroundthisviewpoint,inwhichwe
createdgeneric operationsthathandlethesameoperationfor
differentdataobjects,andusedthetagonthedataobjectto
dispatchtotheappropriateversionoftheproceduretohandle
thatkindofdata.
Slide 13.1.10
Butgiventhistable,thereisanalternativepossible
organization,whichisaroundthecolumnsofthetable.This
wouldfocusoncreatingageneric data objectthatwouldknow
howtohandledifferentoperationsonthatkindofdata
structure.
Slide 13.1.11
Let'sstepbackandrethinkdata.Thissoundslikeanoddthing
todobutlet'sthinkaboutdatainaverydifferentway.Rather
thanthinkingofdataabstractionsassomeslotsintowhichwe
canputthings,let'sinsteadconsiderdatatobeaprocedurewith
someinternalstate.
Thissoundsstrange!But,whatisaprocedure?Itreallyhastwo
parts:ithasasetofparametersandabodywhichdefinethe
patternofcomputationtoperformasafunctionoftheobjects
passedin;andaswesawintheenvironmentmodel,ithasan
associatedenvironmentwhichcanholdname-valuebindings,
thatis,pairingsofnamesandvalues.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.1.12
Sowhat,yousay!Well,wecanusethisideatocapture
informationaboutadatastructure.Inparticular,wecanusea
proceduretorepresentdataobjectswithstate.Whatwouldthat
mean?Itwouldsaythatwecouldusethelocalenvironmentof
theprocedureplusitsparameterstoholdthevaluesofthe
datum,andwecouldcreatelocalprocedureswithinthedata
proceduretomanipulatethesevalues,tochangethestateofthe
object.
Thismeansthattheonlyaccesstothevaluesofthedataobject
willbethroughtheprocedurerepresentingthedata.Thiswould
nicelyencapsulatethedatastructureinsidethisprocedure.
Thisprobablystillsoundsoddsolet'slookataspecific
example.
6.001 Notes: Section 13.2
Slide 13.2.1
Toillustratethisideaofusingaproceduretorepresentadata
structure,anobjectwithstate,let'slookatthefollowing,rather
odd,example.Hereisaverydifferentwayofimplementinga
conscellorapair.Letmestressthatthisisnotthewaythat
Schemenormallyrepresentspairs.Ofcourse,theideaofdata
abstractionisthattheactualimplementationofadatastructure
shouldbeirrelevanttotheuser.Thisexampleisusedtodrive
homeaconceptualpoint.
Here,wehaveimplementedapairasaprocedure!Thusour
fundamentaldatastructureisnowaprocedureratherthansome
storageinmemoryslots.
Slide 13.2.2
Lookatthiscarefully.First,notethatcons,asdefinedhere,
involvestwolambdas.Rememberthatthereisahidden
lambdainsidethesyntacticsugarofthisdefinition.This
meansthatthereisasecondlambda asthebodyofthe
cons andthuswhenweevaluate(cons x y)using
thisparticularimplementation,wegetbackasavalue,a
procedureofoneparameter,msg.
Sowhatdoesthissay?Itsaysthatwhenweuseconswith
thisimplementationourrepresentationforourfundamentalway
ofgluingthingstogetherisnowaprocedureofoneargument.
Sowhatwouldthatcons thingdo?Sinceitisaprocedure,ifwesenditavalue,orifweapplytheprocedureto
asingleargument,notewhatitdoes.Itusesthevalueoftheargument,inthiscaseaparticularsymbol,todecide
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
whatvaluetoreturn.
Wecallthisstyleofprogramming,message passing,becausetheprocedureacceptsamessageasinput,andthen
doessomethingbasedonthevalueofthatmessage.
Slide 13.2.3
Thislooksabitweird!Ourconstructorforgluingthings
togethergivesusaprocedureastheactualobject.Shouldwe
care?
Ofcourseweknowthatweshouldn'tcare.Tocompletethe
abstractionforapair,wesimplyneedtocreatecarandcdr
tofulfillthecontractoftheabstractionofapair.
Eachofthoseisitselfaprocedurethattakesasinputapair,
whichweknowisaprocedure,andthenappliesthatprocedure
toasingleargument,whichinthiscaseisjustasymbolic
message.Ideally,thatmessageshouldgetbackforusthevalue
weneedtosatisfythecontract.Ifwelookatthisdefinitionfor
car,weseeittakesasinputoneofthesenewpairs,andthenappliesthatpair(aprocedure)tothesymbolcar,
which inprincipleshouldreturnforusthevalueweusedwhenwecreatedthepair.
Notetheotherprocedurewebuilthere.Ourpredicatefortestingwhethersomethingisapairnowreliesonthepair
identifyingitself.Thisistheversionofourtag.Beforeweattachedatagasasymbolonadatastructure.Here,our
tagsarepartoftheprocedure.
Slide 13.2.4
Tocheckitout,let'stakethisstrangeimplementationofpairs
andverifythatthisimplementationsatisfiesthecontractfora
pair.
Slide 13.2.5
Totestthis,letsconstogetherthenumbers1and2,andgivethe
resultingpairthenamefoo.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.6
Sohereisanenvironmentdiagramthatwouldrepresentthe
stateoftheworld,beforewedothisdefinition.Intheglobal
environment,wewouldhaveabindingforconsasa
procedure,basedonthepreviousslide.
Slide 13.2.7
Whathappenswhenweevaluatethisexpression?Sincecons
isjustaprocedure,evaluating(cons 1 2)saystoapply
theprocedureassociatedwithconstothearguments1and2.
Thus,wedropaframe,scopeitbytheenvironmentpointerof
theprocedure,bindtheformalparameters(xandy)ofthe
proceduretothevaluesofthearguments,andrelativetothat
newframe,andevaluatethebodyoftheprocedure.Thatbody
isitselfalambda!Soitmakesanewprocedureobject,
whoseenvironmentpointerpointstotheframeE1becausethat
iswherethelambdawasevaluated.Then,theprocedure
objectisreturnedasthevalueofthecons.Finally,thedefine bindsfoo intheglobalenvironmenttothis
returnedvalue,thisprocedureobject.
Slide 13.2.8
Noticewhatthisdoes.Itgivesusanobjectinthisenvironment,
wherebyobjectImeanthethingenclosedinred,whichisa
procedurethathasalocalframewithsomebindingsorvalues
withinit.Thus,xbeingboundto1,andy beingboundto2
constituteslocalstateinformation.Thatframeisscopedbythe
globalenvironment,andtheprocedurethatpointstoallofthis
isreferredtobyanameintheglobalenvironment.Thus,from
theperspectiveofauserinteractingattheglobalenvironment,
foo referstoastructurethathaswithinitinformationabout
whatisthefirstpartoftheobject(1)andwhatisthesecond
partoftheobject(2).Itshouldalsohaveinformationabouthow
toextractthosevaluesfromthestructure.
Sothispattern:ofaprocedurethatacceptsmessages,hasaccesstoalocalframewithstateandmethodstoextract
thatlocalstate;isaverycommonpatternthatwearegoingtousealot.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.9
Nowallwehavetodoischeckthatthecontractholdsforthis
dataabstraction.Indoingso,wewillseehowthisstructureofa
procedurewithaccesstolocalstatecapturesexactlythe
behaviorwewant.
Tocheckthis,letsevaluate(car foo).Weknowthatthis
shouldgetconvertedinto(foo 'car),sohowdoesthis
happen?
Slide 13.2.10
Evaluating(car foo)intheglobalenvironmentsimply
appliestheprocedurethatisthevalueassociatedwithcar to
thevalueoffoowhichistheprocedureobjectshown.Now
thedefinitionofcar showsthatthisreducestoevaluatingthe
bodyofcarnamely(foo 'car)withrespecttosome
newenvironment.
Slide 13.2.11
...andwhatdoesthatdo?Itsaystoapplythevalueassociated
withfoo,whichisaprocedure,sothestandardenvironment
modelsaystodropaframe,andscopeitbytheenvironment
pointeroffoo.ThisisimportantasE3nowpointstoE1.
InsideE3webindtheparametermsg totheargumentcar.
Relativetothisframeweevaluatethebodyoftheprocedure
representedbyfoo.Butthatisjustacond clausethatlooks
atthevalueofmsgandcomparesittoasetofsymbols.Inthis
case,thecond saystoreturnthevalueofxwithrespectto
thisframe,whichisjust1.ThisisexactlywhatIwanted,asit
showsthatmycontractissatisfied.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.12
Sowhatdoesallthissay?Asidefromshowingthatourcontract
isfulfilled,thatwhatwegluetogetherusingthisversionof
cons wecangetbackapartusingcarorcdr,wehave
alsoseenthiscommonpatternthatwecancreateadataobject
representedasaprocedure.Theprocedurehassomelocalstate
capturedinaframethatisaccessibleonlybythatprocedureand
ithastheabilitytoacceptmessagesandbasedonthose
messagesreturninformationfromthelocalstate.Solet'ssee
howtobuildonthatidea.
Slide 13.2.13
Inthecasewejustconsidered,ourproceduresfordata
structurescouldreturnvaluesasafunctionofinputmessages.
Ifwearegoingtousethisideaofmessage-passingprocedures
torepresentinformation,wealsoneedtohavewaysof
changingthevalueofthestatecapturedbythoseprocedures.In
ourpairexample,hereishowwewoulddothis.
Slide 13.2.14
Let'saddtwomoremessages,ortwomorewaysofdealingwith
messages,toourconstructor,cons:onefordealingwith
mutatingthecarandonefordealingwithmutatingthecdr.
Noticethatinthiscaseweneedsomethingdifferent.Ifthe
cons pair(i.e.oneoftheseprocedures)getsthemessage
set-car!wearegoingtoreturnaprocedurethatwill
takeanewvalueforthecar andchangetheoldvaluetothis
newvalue.
Thisisadifferentbehaviorfrombefore.Nowamessagegetsus
backaprocedureratherthananumber.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.15
Asaconsequence,theprocedureset-car!musthavea
newform.Asbefore,itwilltakeapairandanewvalueas
arguments,butnowitsendsthepair(thatprocedure)the
messageset-car!,whichgivesustheprocedureneeded
tochangevalues,andwethenapplythatproceduretothenew
value.Youcanseethatthedefinitionaccomplishesexactlythis.
Slide 13.2.16
Solet'stracethisthrough.Hereisadefinitionforbartobe
thecons of3and4,andhereistheglobalenvironmentin
whichwearegoingtodothis.
Slide 13.2.17
Whenweevaluatethisexpressionwesimplygetastructure
similartowhatwesawbefore,abindingofbar toa
procedurewithsomelocalstate.Thus,wehavebarasa
message-passingobject.
Slide 13.2.18
Sonowlet'smutatethisobject.Let'schangethecarpartof
thisobjecttobe0.Thenevaluating(set-car! bar
0)reducestoevaluating((bar 'set-car!) 0)
insomeotherframe.Nowhowdoesevaluatingthisexpression
effecttherightmutation?
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.19
First,weneedtogetthevaluesofthesubexpressionswith
respecttothisframe.Wellbarisboundtoaprocedure,sowe
canapplyittothesymbolset-car!.Thisdropsaframe,
scopedbyE4becausebar'sprocedureisalsoscopedthere.
Withinthatframewebindmsg tothesymbolset-car!
andrelativetothatframeweevaluatethebodyoftheprocedure
bar.Thiswillreturnanexpression(lambda (new-
car) (set! x new-car))tobeevaluatedwith
respecttothisframeE6.
Slide 13.2.20
Nowherecomesthecriticalpoint.Rememberthatweare
evaluatingthebodyofbar withrespecttoE6,whichreduced
toevaluating(lambda (new-car) (set! x
new-car)) withrespecttothisframeE6.
This,ofcourse,createsaprocedureobject,whoseenvironment
pointerisscopedbyE6(andthisisthecrucialpoint!).Notethat
thisnewlycreatedprocedureobjectwillhaveaccesstoE6and
bychainingtoE4.Thisprocedureobjectisthevaluereturned
byevaluating(bar 'set-car!).
Slide 13.2.21
...andthisisexactlywhatIwant.Inowapplythisprocedureto
thevalue0,whichisthelastpartoftheoriginalevaluation.By
environmentmodel,Ijustdropaframe,scopedbyE6,binding
new-cartothevalue0.ThusE7isscopedbyE6,whichinturn
isscopedbyE4.RelativetoE7,Inowevaluatethebodyofthis
procedurethatIjustcreated,andthatsays(set! x new-
car)withrespecttoE7.
Slide 13.2.22
Sonowweevaluatethatset! expressionwithrespecttoE7.
Firstwefindthebindingforx,whichwegetbytracingfrom
E7throughE6toE4.Thenwefindthebindingfornew-
car whichwefindinE7,andthenchangethebindingforx
inE4tothisnewvalue.
Noticehowwehavenowmutatedavalueinthelocalstate
associatedwithbar.Thusourprocedurescannotonly
capturelocalstateinformation,theycanalsosupplyprocedures
forchanginglocalstate.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.23
Thisiscertainlydifferentfromourearlierdataabstractions.
Nowwehavedataobjectsthatareactuallyprocedures.Acons
pairisnowaprocedure,andcarorcdrissomethingthat
operatesonaprocedure.Butaswehaveseen,thecons,
car, cdrwejustbuiltsatisfythedataabstraction
contract,andthereforebehaveasexpected.Thekeynewthing
wehaveisaprocedurethatrepresentsdata,andtakesmessages
asinputandreturnseitherdatavaluesorproceduresfor
changingdatavalues.Thisisaveryhandyidea,solet's
generalizeit.
Let'screateprivatestatevariables(aswedidearlier)butalso
privateproceduresthatwillbelongtoeachinstanceofthedataabstraction.
Slide 13.2.24
Noticethedifferenceinthisversion.NowIcreateinternal
procedures(change-car, change-cdr)but
insideofmyactualobject,Inotonlycreatethoseprocedures,I
usetheminsidetheobject.ThishasaniceeffectinthatwhenI
executesomeoperationonanobject,Idon'thavetoremember
whattypeofvalueisreturnedbytheobject(e.g.numberversus
procedure).Inallcases,theuseofthedataobjectisidentical.
Thusnowourselectorsandmutatorsperforminauniform
manner.
Before,wehadtorememberwhethertheobjectreturneda
valueoraprocedure,inordertocompleteourmanipulation.
Here,theselectorsandmutatorsjustsendamessagetotheobjectandwithintheimplementationoftheobject,we
takecareofthenecessaryworktoeitherapplyaninternalprocedureortosimplyreturnavalue.
Noticethatbydefiningtheinternalprocedureswithinthecontextoftheconswewillcreateproceduresthatare
scopedwithinthecreatedbycallingthecons.Thus,theseprocedureswillbelongonlytothisinstanceofthe
dataobject.
Bymakingauniforminterfaceformutatorsandselectorswehaveintroducedoneotherthingintooursystem.In
particularwenowneedourselectorsandmutatorstodealwithdifferentnumbersofarguments,andyetwewould
likeourdataabstractiontobeasingleprocedure.Soweneedawayoflettingalambdaspecifythatitwantsto
takeanarbitrarynumberofarguments.Thatisthe"funny"notationyouseeof(lambda (msg .
args) body),whichwedealwithonthenextslide.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.25
Upuntilnow,everyprocedureyouhavewrittenhasrequired
thatyouspecifynamesofalltheinputparameters,andasyou
haveseen,ifyoucalltheprocedurewiththewrongnumberof
argumentsitcausesanerror.Wewouldlikeamechanismthat
letsaproceduretakeanarbitrarynumberofarguments,suchas
youhavealreadyseenwithbuilt-inprocedureslike+.
Slide 13.2.26
SoSchemeprovidesawayofdoingthis.Toseethis,let's
define(add x y . rest)tobeaprocedurethatis
goingtoaddabunchofthings.Here,thesyntaxisanargument
xanargumenty andthenadot(.)andthentheargument
rest.Andthebehaviorisasfollows:Ifweapplyadd toa
setofarguments,thevalueofthefirstargumentwillbebound
tothevariablex,thevalueofthesecondargumentwillbe
boundtothevariabley andthevaluesoftheanyother
argumentswillbebound,asalisttothevariablerest.
Thusifweevaluate(add 1 2)thenx isboundto1,yis
boundto2,andrestisboundtoanemptylist.Ifwetrytoevaluate(add 1)wewillgetanerror,because
inthisformat,thefirsttwoargumentsarerequired,i.e.wemusthavesomethingforbothxandy.Butifwe
evaluate(add 1 2 3),thenx willbeboundto1,ywillbeboundto2,andrestwillbeboundtothelist
(3).Andifweevaluate(add 1 2 3 4 5)inthiscaserestwillbeboundtothelist(3 4 5).
Thusinthisnotation,alloftheparameterspriortothedotmusthaveavaluepassedin,theparameterafterthedot
willbeboundtothelistofthevaluesofalltheremainingarguments.
Slide 13.2.27
Ifwecomebacktoourexample,weseethatifwejusttakethe
carofapair,msg willbeboundtothesymbolcar,and
restwillbeboundtotheemptylist.Ontheotherhand,ifwe
wanttomutatethecarofapair,thenmsgwillbeboundtothe
symbolset-car!,andargswillbeboundtothelistof
onevalue,thenewvaluetobeused.Withintheprocedurethat
definesthecons,noticewhathappens.Ifwearegoingto
executeaset-car!,weapplytheinternalprocedure
change-cartothefirstvalueinthelistargs.Inother
words,itwillextracttherightvaluetouse,andcausethe
appropriatechange,itwillmutatethebindingofxtobethatnewvalue.Andthuswecanapplytheseinternal
procedurestotheappropriatevalues,whilepreservingauniformexternalinterface.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.2.28
Sincewehavebeenthrowingalotofdetailsatyou,let'sstep
backforamoment.Whatwehavenowseenisamethod,using
aparticularexampletoillustrate,forcreatingaprocedurethat
captureslocalstate.Thisproceduretakesinamessage,and
basedonthatmessageandpossiblysomeotherarguments,
eitherreturnsvaluesbasedonthelocalstateoritcauses
changesinthatlocalstate.
Thisnewmethod,thisideaofamessagepassingprocedure,
let'suscaptureinformationaboutadatastructureinsidea
procedureitself.
Slide 13.2.29
Sowhatdoesthissay?Wehaveintroducedthebasicideaofa
newstyleforapproachingcomputationalsystems.Our
traditionalstyleisproceduralprogramming:weorganizethe
systemaroundtheproceduresthatoperateonthedata.Thekey
isthatweisolatethedatainstandardlist-likestructures,with
tags,thenfocusonthinkingaboutwhatmethodsorprocedures
wewanttousetomanipulatethevalueswithinthosestructures.
Slide 13.2.30
Herewehaveshownthebasisforanewapproach,whichis
orientedaroundthedataobjectsthemselves.Notewhatwedid
withourexampleofapair.Wefocusedoncapturingthe
informationwithinastructure,wheretheoperationsto
manipulatethedatawereassociateddirectlywiththatstructure.
Moreimportantly,thebasicconceptualunitwasthedataobject
itself.Whatmessagesshouldanobjecthandle?Whatoperations
shouldanobjectsupport?Howshouldwecapturethose
methodsinternallywithintheobject?
Slide 13.2.31
Sowhichapproachisbetter?Itdependsontheproblem
domain!Proceduralmethodsareverygoodwhenweare
dealingwiththingslikenumericaloperationsorwhenweare
dealingwithsystemswithverysmallnumbersofdata
structures.
Ontheotherhand,objectorientedsystemsareverygoodfor
thingslikesimulationsorforsystemswithlargenumbersof
objects,wheretheobjectsarecharacterizedbyasmallamount
ofstateinformationandthecomputationbasicallyinvolves
interactionbetweentheobjects,causingthatstatetochange.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
6.001 Notes: Section 13.3
Slide 13.3.1
Wehaveseenlotsofexamplesofthefirststyleofprogramming
inthefirstpartofthecourse.Nowwearegoingtospendsome
timeexploringthesecondstyle.Whatdoesitmeantocreatean
object-orientedsystem?
Todiscussthis,weneedsometerminology:Inanobject-
orientedsystem,wewilltalkaboutaclassandaninstance.A
classcapturesasetofobjects,withcommonbehavior.For
instance,cons inourpreviousexamplewasaclass.By
convention,touseaclasswewillhaveamakerprocedurethat
createsinstancesofthisclass.
Aninstancewillbeaparticularandspecificversionofaclass.
Forexample,fooorbarinourearlierexampleswereinstancesofthecons class.Aninstancetakes
messagesinthemannerdefinedbythemakerprocedureandusesthemtomanipulatetheparticularvaluesofthe
instance.Soweexpectasaconsequencetohavelotsofinstancesofaparticularclassinoursystem.
Slide 13.3.2
Sohereisagoodwaytoconceptualizetheseideas,andin
particularthedifferencesbetweenthem.Associatedwithaclass
willbeaclass diagram.Thiscontainsinformationsuchasthe
nameoftheclass(pair),theprivatestatethatbelongstothe
class(xandy),aswellaswhatpublicmessagesare
recognizedbythisclass(car, cdr, pair?, set-
car! andset-cdr!).Notethatthesepublicmessages
definetheinterfacetotheclassofobjects.Thisclassdiagram
thuscapturestherelevantinformationaboutaclass.
Slide 13.3.3
Thusinourearlierexample,consdefinesaclass.Our
previousdefinitionforcons isourparticularwayof
implementingthisclass,orconstructingelementsofthisclass.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.4
Andthatleadsnaturallytotheideaofaninstance.Whenwe
usethemakerassociatedwiththisclass,wecreateparticular
instancesoftheclass,orexamplesfromthisclass.Wecan
representdiagrammaticallyinaninstance diagram.Within
thatdiagram,wewillhaveinformationaboutthetypeofeach
instanceaswellasspecificvaluesfortheinternalstateofeach
instance.Notethatthesevaluescouldthemselvesbeother
instancesofclasses.
Slide 13.3.5
SoifIdefinetheexampleexpressionshown,inmyinstance
diagramIcreatetwoinstancesoftheclasspair,bothcreated
bythemakerprocedurecons.Withineach,Ihavebindings
for,orspecificvaluesfor,theinternalstateassociatedwitheach
instance.Noticehowthesebindingscanbesimplevalueslike
numbersorpointerstootherinstancesofclasses.
Soweseethataclassdefinesasetofobjectsandaninstanceis
aparticularversionofanobjectfromsomeclass.
Slide 13.3.6
SohowdoIusetheideasofclassesandinstancestostart
designingasystem?Let'ssuppose,asanexample,thatIwantto
buildasimulatorforastarwarsgame:itwouldhaveshipsthat
couldflythroughspace,landonplanets,shoototherships.
IcanstartbythinkingaboutwhatkindsofobjectsdoIneed?
ThatwilltellmewhatkindsofclassIneedandwhatstate
informationisneededforaclassandwhatinterfacesbetween
classesareneeded.Itmightsay,forexample,thatIwantsome
ships.Sinceshipswillneedtomove,thishelpsmedecidewhat
kindofstateashipwillneed.
ThusIbeginthinkingaboutthesystemintermsofwhatkinds
ofobjectsandwhatinformationassociatedwiththoseobjects
doIwant.Icanthenextendthistostartthinkingaboutparticularinstancesofobjects.Howmany,whatstatefor
each,andsoon.
Solet'sseehowtheideaofaclass,andinstancesofaclass,canbeusedtodesignanobject-orientedsystem.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.7
Wewilluseourstarwarssimulatortoexploretheuseofclasses
andinstancesofclassestobuildobject-orientedsystems.The
firstclassofobjectsinmysystemwillbeships.Sohereisa
procedureformakinginstancesoftheclassofships.This
makerproceduredefinestheactualclass.
Slide 13.3.8
Giventheideaofaship,Icanturntothequestionofwhat
behaviorIwantforinstancesofthatclass.Clearlyashipneeds
tobeabletomove.NotethatthisthentellsmethatIwillneed
someinformationaboutwheretheshipcurrentlyliesandhowit
ismoving,aspartoftheclassdefinition.Inthiscase,Ichoose
topassthatinformationin,whenIactuallyconstructthe
instance.SothistellsmeIwillneedposition,
velocity andmaybesomeotherthingsasinputstothe
classconstructor.
Actually,Iamcheatinghere.Iknowthatinordertomove,I
needtohavethatkindofinformationaspartoftheclass,butin
factIcouldhavecreatedaconstructorwithnoparameters,andsimplyhavewithinitaletclausethatcontained
initialdefaultvaluesforthepositionandvelocity.
NoticehowthinkingaboutwhatIwantmyobjectstodohelpsmetodecidewhatinformationshouldbecaptured
aslocalstate,andwhatinformationshouldbepassedinwhenIcreateinstancesofthisclass.
Slide 13.3.9
Andwhatabouttheclassitself?WhenIusethismaker
procedure,itwillreturnaninstanceofaship,whichwillbe
representedbyoneofthesemessage-passinglambdas.
Notetheform.Ittakesasinputamessage,andeitherreturns
informationaboutthestateoftheship,orcausesoneofthe
internalprocedurestobeexecuted.Thislooksalotlikethe
generalizedformweusedforourconspairearlier.
Similarly,wewillhaveinternalproceduresformanipulatingthe
datavalues,verymuchlikeourconsexample.Theonly
otherthingtonoteishowthelastclauseofourmessagepassing
procedureisabailoutclause.Itsays:ifyougivemeamessage
thatIdon'trecognize,I'llletyouknowsothatyoudon'ttrytodosomethingyoucan't.
Thushereisadefinitionofaclass:amakerprocedurethatcreatesships.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.10
Solet'sgatherthattogetherinourclassdiagram.Hereisthe
classdiagramofaship,basedonthatdefinition,includingstate
variables,andmessagesformanipulatingthosestatevariables.
Thosemessagesnowdefinetheinterfacetoinstancesofthis
class.
Slide 13.3.11
Nowwecanmakesomeinstances,asshown.Ofcourse,weare
assumingsomeabstractionforvectors,whichwecouldeasily
define.Notethatbyusingtheclass'smakerprocedure,Ihave
createddifferentinstances,eachwithitsownstatevariablesand
itsownproceduresformanipulatingthatstateinformation.The
interfacestotheseinstancesaredefinedasthesetofinterfaces
fromtheclassdefinition.Eachoftheseobjectswillacceptthe
samesetofmessages,butcasetheirown internalstateto
change.
Slide 13.3.12
Toseethis,let'suseourenvironmentdiagramtoseehowour
simulationevolves.Wewanttoseebothhowinstancesare
genericallymaintainedinthesystem,aswellasexaminingthe
detailsofourparticularimplementation.Let'sevaluatethese
threeexpressionsinorder,toseehowourclassescreate
instances,andhowthoseinstanceskeeptrackofstate
information,asoursimulationmovesforward.
Slide 13.3.13
First,wewilluseourmake-ship proceduretocreatean
instanceoftheclass.Evaluatingthatfirstexpressioncreatesa
frame,throughtheapplicationoftheprocedure,inwhichthe
formalparametersareboundtothevaluesofthearguments
passedin.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.14
Havingcreatedthatframe,wethenevaluatethebodyofthe
procedurewithrespecttoit.Notewhatthatdoes.Theinternal
definitionscauseabindingofavariableinthisframetothe
valueshown,inparticular,move getsboundtoaprocedure
whoseenvironmentpointerpointstothisframe.Thus,wehave
aninternalprocedure,whichwillhaveaccesstothelocalstate
variablescapturedinthisframe.
Slide 13.3.15
Thus,thosetwointernaldefines createbindingsfor
namesinthatframethatpointtolocalprocedureswithaccessto
thebindingsofthisframe.Thusthisframecontainsinformation
aboutthisinstanceoftheclass,thestatevariablesandthelocal
methodsthatwillbeusedtochangethosevariables.
Slide 13.3.16
Havingevaluatedthelocaldefines,wethenevaluatethe
restofthebodyofthisconstructor,make-ship.That
evaluatesthatlastlambda,creatingaprocedureobject
whoseenvironmentpointeralsopointstothisframe,anda
bindingforthenameintheglobalenvironmentthatpointsto
thisprocedureobject.Again,wegetamessage-passingobject
withlocalstateandmethodsforchangingthelocalstate.
Slide 13.3.17
Supposeweaskthisparticularinstanceofashiptomove.This
saystosendtheprocedurerepresentingthisshipthemessage
move,andweknowthatthisreducestoevaluatingtheactual
proceduremovewithrespecttothisframe.Applyingthat
procedurecreatesaframe,eventhoughtherearenoarguments
tobind,andrelativetothisframeweevaluatethebodyof
move.Thisthensaystochangetheposition.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.3.18
Andofcourseevaluatingthebodyofthisprocedurecausesus
tomutatethecurrentvalueforposition.Justaswesaw
withourconsexample,wehavechangedthestateofour
instance.Thus,ifweaskforthepositionofourobjectnow,we
willgetthisnewvalueastheanswer.
Thus,ourlocalinstanceofashipcaptureswithinitstate
informationandprocedurestochangethatstateinformation.
Theactualinstanceobjectisaprocedurethatusesmessagesto
determinewhattodo.
6.001 Notes: Section 13.4
Slide 13.4.1
Thekeythingtonoteishowwecanuseobjectstomodularize
ourdesign.Noticeinthepreviouscasethatwecanleavesome
methodsblankandstilltestoursystem,aswecanjustfillthese
methodsinwhenweneedthem.Alsonoticehowweusethe
ideaofwhatthingswewantedtheobjecttobeabletodoto
definewhatstateinformationweneeded,andwhatmethodswe
neededtodealwiththatinformation.Solet'sbuildonthisidea
toseewhatothercapabilitieswecanadd,andhowthinking
aboutthingsintermsofclassesofobjectsandinstancesof
thoseclassesallowsustoeasilydesigninteractivesystems.
Slide 13.4.2
Sowhatkindsofthingscouldweaddtooursystem?
First,wecouldaddnewclasses,forexampleaplanetclass,
whichshouldhaveadifferentbehaviorfromships.
Second,weforgottoallowfortypesandtagsinoursystem.
Thismeansweneedtoaddpredicatemessagesandmethodsso
thatobjectscanidentifytheirtype.NotethatthisarisesonceI
addmorethanonekindofobjecttomysystem(e.g.withjust
shipsImightnotneedit,butonceIaddplanetsIhaveto
distinguishbetweentypesofobjects).
Andwemightwantadisplayhandler,somethingthatdrawsthe
positionofmyobjectsonascreen.Thiswewillseecanbe
implementedasaprocedure,sothatnoteverythingneedstobe
anobjectinoursystem.Todothis,wewillneedtomodifyourclassessothateveryobjectcandisplayitselfon
demand.
Withthisframeworkformodifyingoursystem,let'sseehowonegoesaboutextendingobject-orientedsystems.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.4.3
Ifweaddplanetstooursystem,wewillhaveanewclass
diagram.Inadditiontoourearlierclass,wenowhaveaclass
forplanets,withsomestateinformationandsomemethodsfor
manipulatingthatinformation.Noticethataspartofourdesign
weaddtwonewthingstoboththisclassandouroriginalship
class:apredicatefortestingtypes,andamethodforhandling
display.
Nowwatchhowwecanaddnewinstancestooursystemand
howwecaneasilyreturntoouroriginaldesignandmodifyitto
addnewcomponentsandmethods.
Slide 13.4.4
Tostart,hereisourmakerprocedurefortheplanetclass.Note
thattheonlylocalinformationisposition andthe
instanceswillrecognizethreemethods.Hereisourfirstversion
ofapredicate:themessageplanet?willreturnthetrue
value,toindicatethatthisobjectisofthattype,hencewehave
anewwayoftaggingobjects.Andnoticehowwecanadd
methodsthatsimplyexecuteaprocedurewithoutreturninga
value.Heredrawisusedforthesideeffectofgraphically
displayingtheplanet.
Noteinparticularhowplanet?isdefiningtheequivalent
ofatypetag.
Slide 13.4.5
Nowthatwehaveseensomesimpleextensionstoourworld,
whatelsecanweadd?Well,theoriginalmotivationfor
buildingthissystemistoenablelargesystemsofdifferent
kindsofobjectstointeract.Wewouldliketosetupoursystem
sothatwecancreateabunchofobjects,initializetheirstate,
andthenlettheobjectsinteractinasimulationofsome
dynamicevolution.
Todothis,wejustaddonenewobject:aclock.Ifwethenkeep
trackofeverythinginouruniverseofinstances,wecanhave
theclocksynchronizetheevolutionofeachobjectbysendingit
amessagetoupdateitsstate,whichitwilldothroughitsown
localprocedure.
Andtoaddsomespicetooursystem,wewillletshipsshootateachother,sowewilladdanewclass,atorpedo.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.4.6
Ifweaddtorpedoesweneedtoupdateourclassdiagram,and
hereitis.Noticethatthisclasssharesalotofcommon
informationwithships,apointtowhichwewillreturnlater.
Thetoplevelpointtonoteishowourdesignisevolving.We
startedwithasingleclass,andhavenowaddednewclassesas
ourdesiresforthesystemexpand.Eachclasshasasetoflocal
statevariables,andmethodsthatitiscapableofhandling.
Theotherchangetoourclassdiagramistheinclusionofanew
methodforeachobject,theabilitytoacceptasynchronization
signalfromtheclock,andthenupdatestate.
Again,notehowourdesignisevolving.Wecanaddnew
classes,andwecanextendexistingclassesbyaddingnew
methodsasourdesiredbehaviorsforthesystemdemandthem.
Slide 13.4.7
Wealsoneedawayofcoordinatingtheactionsandinteractions
ofobjectsinouruniverse. Onewaytodothisistouseaclock,
whichcouldsendasignaltoeachobjecttosynchronizethe
passageoftime. Forexample,aclocktickcouldcauseaship
tomoveasmallamount,orfireatorpedo,orlaunchashuttle.
Thereareseveralwaystoaccomplishthis;hereisasketchof
one. Ourclockmaintainsalistofthingstodooneachtickof
theclock. Inparticular,itdoesthisbystoring,asinternalstate,
alistofcallbacks,thatis,messagestosendtospecificobjects
toexecutespecificactions.
Wecanthensimulateourworldbyrunningtheclockthrougha
sequenceofticks. Oneachtick,theclockwalksdownitslistof
callbacks,andaskseachtoactivate. Intuitively,thismeansthatitasksasetofobjectstopassmessagestotarget
objects,likeourships.
Slide 13.4.8
Tomakethishappen,wesimplyneedtocreateanewobject,a
callback. Thisissimplyanewobjectthatstoresatarget
object,amessageandasetofarguments. Whenactivated(by
theclock),itsendsthetargetobjectthemessage,whichwill
causesomethingtohappenintheworld. Itcanbethoughtofas
abuttonthatexecutesanactioneverytickoftheclock. The
detailsarenotcrucial,whatmattersistheideathatasingle
object,aclock,cancontrolanothersetofobjects,the
callbacks,thatsynchronizetheactionsofobjectsinthe
universe.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.4.9
Wecanalsoevolveourclassdefinitions.Giventhatwewantto
addsomenewcapabilitiestoourships,wereturntothemaker
procedureandchangeit.Forexample,wecanaddamethodto
firetorpedoes,togetherwithmethodsthatupdatethestate
associatedwithtorpedoes.Alsonoteaspartofthishowweuse
amakertocreateatorpedo,andaddingthetorpedotothe
universewillpresumablycausethetorpedotosendacallback
messagetotheclocksothattheclockcankeeptrackofit.
Wealsoneedtoallowshipstoexplode,andnoticetheform
here.Theactualprocedureexplode takesasargumenta
ship,whichneedstoberemovedfromtheuniverse.Noticehow
tosupportthiswehavechangedthedefinitionofourmessage
passingobjecttousethat"dotted"argumentnotation,sothatwecanpassinarbitrarynumbersofargumentstoan
object.Weusethatheretoallowforthefactthatifsomethingcollidesinouruniverse,weasktheobjectto
"explode"andwepassinthepointertotheobjectitself.Thus,inthemethod,wecanthenremovethatobjectfrom
theuniverse(ifithasexplodeditshouldn'tstayaroundforfurthersimulation!).Thuswehaveawayofpassing
objectsasargumentstootherobjects.
Finally,notehowwesendacallbackobjecttotheclock,whichwillcreateamessagetobesenttothisobjecton
eachclocktick,inthiscase,justaskingthisshipobjecttomove.
Slide 13.4.10
Sowearealmostdone.Weneedtohavesomethingthatmakes
instancesoftorpedoes.Notethatithasalotofthesameformas
aship,buthasitsowninternalproceduresforexplodingandfor
moving.
Slide 13.4.11
Havingdoneallofthis,wecannowrunalittlesimulation.We
createsomeinstancesofobjects,weaddthemtothisuniverse,
andthenjustruntheclocktostartthesimulation.
6.001StructureandInterpretationofComputerPrograms.Copyright2004byMassachusettsInstituteofTechnology.
Slide 13.4.12
Soherearethekeymessagestotakeawayfromthisexercise.

You might also like