using prototypical objects to implement shared behavior in object oriented systems, henry lieberman
DESCRIPTION
A traditional philosophical controversy between representing general concepts as abstract sets or classesand representing concepts as concrete prototypes is reflected in a controversy between two mechanismsfor sharing behavior between objects in object oriented programming languages. Inheritance splits theobject world into classes, which encode behavior shared among a group of instances, which representindividual members of these sets. The class/instance distinction is not needed if the alternative of usingprototypes is adopted. A prototype represents the default behavior for a concept, and new objects can reuse part of the knowledge stored in the prototype by saying how the new object differs from theprototype. The prototype approach seems to hold some advantages for representing default knowledge,and incrementally and dynamically modifying concepts. Delegation is the mechanism for implementingthis in object oriented languages. After checking its idiosyncratic behavior, an object can forward amessage to prototypes to invoke more general knowledge. Because class objects must be created beforetheir instances can be used, and behavior can only be associated with classes, inheritance fixes thecommunication patterns between objects at instance creation time. Because any object can be used as aprototype, and any messages can be forwarded at any time, delegation is the more flexible and general ofthe two techniques.TRANSCRIPT
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 1/19
UsingPrototypicalObjectstoImplementSharedBehaviorinObjectOrientedSystems
HenryLieberman
ArtificialIntelligenceLaboratoryMassachusettsInstituteofTechnology
Cambridge,Mass.02139USA
Electronicmail:
Abstract
Atraditionalphilosophicalcontroversybetweenrepresentinggeneralconceptsasabstractsetsorclassesandrepresentingconceptsasconcreteprototypesisreflectedinacontroversybetweentwomechanismsforsharingbehaviorbetweenobjectsinobjectorientedprogramminglanguages.Inheritancesplitstheobjectworldintoclasses,whichencodebehaviorsharedamongagroupofinstances,whichrepresentindividualmembersofthesesets.Theclass/instancedistinctionisnotneededifthealternativeofusingprototypesisadopted.Aprototyperepresentsthedefaultbehaviorforaconcept,andnewobjectscanreusepartoftheknowledgestoredintheprototypebysayinghowthenewobjectdiffersfromtheprototype.Theprototypeapproachseemstoholdsomeadvantagesforrepresentingdefaultknowledge,andincrementallyanddynamicallymodifyingconcepts.Delegationisthemechanismforimplementingthisinobjectorientedlanguages.Aftercheckingitsidiosyncraticbehavior,anobjectcanforwardamessagetoprototypestoinvokemoregeneralknowledge.Becauseclassobjectsmustbecreatedbeforetheirinstancescanbeused,andbehaviorcanonlybeassociatedwithclasses,inheritancefixesthecommunicationpatternsbetweenobjectsatinstancecreationtime.Becauseanyobjectcanbeusedasaprototype,andanymessagescanbeforwardedatanytime,delegationisthemoreflexibleandgeneralofthetwotechniques.
1.Setsvs.prototypes:aphilosophicaldilemmawithpracticalconsequences
Howdopeoplerepresentknowledgeaboutgeneralizationstheymakefromexperiencewithconcretesituations?Philosophersconcernedwiththetheoryofknowledgehavedebatedthisquestion,butasweshallsee,theissueisnotwithoutpracticalconsequencesforthetaskofrepresentingknowledgeinobjectorientedsystems.Becausemuchofobjectorientedprogramminginvolvesconstructingrepresentationsofobjectsintherealworld,ourmechanismsforstoringandusingrealworldknowledgegetreflectedinmechanismsfordealingwithobjectsincomputerlanguages.We'llexaminehowthetraditionalcontroversybetweenrepresentingconceptsassetsversusrepresentingconceptsasprototypesgivesrisetotwomechanisms,inheritanceanddelegation,forsharingbehaviorbetweenrelatedobjectsinobject
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 2/19
orientedlanguages.
Whenapersonhasexperienceinaparticularsituation,sayconcerningaparticularelephantnamedClyde,factsaboutClydecanoftenproveusefulwhenencounteringanotherelephant,sayoneFred.Ifwehavementalrepresentationsofaconceptfor(Clyde,andaconceptforFred,thequestionthen:HowdotherepresentationsofClydeandFredshareknowledge?Howcanweanswerquestions,suchasFred'scolor,numberoflegs,size,etc.byreferencetowhatwealreadyknowaboutClyde?Intheabsenceofanymechanismforsharingknowledgebetweenrelatedconcepts,we'dhavetorepeatalltheknowledgeaboutClydeinarepresentationofFred.
Therearetwopointsofviewwecanconsideradopting.Thefirstisbasedontheideaofabstractsets.FromlearningaboutClyde,wecanconstructaconceptoftheset[orclass]ofelephants,whichabstractsoutwhatwebelieveistrueaboutallindividualanimalssufficientlysimilartoClydetobecalledelephants.Thedescriptionofthesetcanenumerateallthe"essential"propertiesofelephants.WecanviewClydeasamemberorinstanceofthisclass.Inanobjectorientedsystem,thesetapproachinvolvescreatinganobjecttorepresentthesetofelephants,andestablishingalinkrepresentingthemembershiprelationbetweentheobjectrepresentingClydeandthesetobject.Sincethedescriptionofthesetrepresentswhatistrueaboutallitsmembers,wecananswerquestionsaboutClydebyreferringtothedescriptionoftheset.EstablishingthesamekindofmembershiplinkbetweenFredandthesetofelephantsenablesFredandClydetosharesomeofthesameknowledge.IfFredandClydesharesomeadditionalproperties,suchasthatofbeingIndianelephants,thatarenotsharedbysomeotherelephants,thesecanbeembodiedinasubclassobject,whichsharesallthepropertiesoftheelephantset,adjoiningtheadditionalpropertiesrelevanttoIndia.
Butthere'sanalternativepointofview.WecanconsiderClydetorepresenttheconceptofaprototypicalelephant.IfIaskyouto"thinkofanelephant",nodoubtthementalimageofsomeparticularelephantwillpoptomind,completewiththecharacteristicsofgraycolor,trunk,etc.IfClydewastheelephantmostfamiliartoyou,theprototypicalelephantmightbeanimageofClydehimself.IfIaskyouaquestionsuchas"Howmanylegsdoesanelephanthave?",awaytoanswerthequestionistoassumethattheansweristhesameashowmanylegsClydehas,unlessthere'sagoodreasontothinkotherwise.TheconceptofFredcanhaveaconnectionmarkingitsprototypeasClyde,asamechanismforsharinginformationbetweenthetwoweightypachyderms.ThedescriptionofFredcanstoreanyinformationthatisuniquetoFredhimself.IfIask"HowmanylegsdoesFredhave?",youassumetheansweristhesameforFredasforClyde,intheabsenceofanycontraryevidence.IfyouthenlearnthatFredisathreeleggedelephant,thatknowledgeisstoredwithFredandisalwayssearchedbeforereferencetotheprototypeismade.
2.Prototypeshaveadvantagesforincrementallearningofconcepts
Thoughtheconceptofasethasprovenfruitfulinmathematics,theprototypeapproachinsomewayscorrespondsmorecloselytothewaypeopleseemtoacquireknowledgefromconcretesituations.Thedifficultywithsetsstemsfromtheirabstractnesspeopleseemtobealotbetteratdealingwithspecificexamplesfirst,thengeneralizingfromthemthantheyareatabsorbinggeneralabstractprinciplesfirst,andlaterapplyingtheminparticularcases.Prototypesystemsallowcreatingindividualconceptsfirst,thengeneralizingthembysayingwhataspectsoftheconceptareallowedtovary.Setorientedsystemsrequirecreatingtheabstractdescriptionofthesetfirst,beforeindividualinstancescanbeinstalledasmembers.
Inmathematics,setsaredefinedeitherbyenumeratingtheirmembers,orbydescribingtheunifyingprinciplesthatidentifymembershipintheset.Wecanneitherenumeratealltheelephants,norarewegoodatmakingdefinitiveliststheessentialpropertiesofanelephant.Yetthemajorimpetusforcreating
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 3/19
newconceptsalwaysseemstobeexperiencewithexamples.IfClydeisouronlyexperiencewithelephants,ourconceptofanelephantcanreallybenodifferentthantheconceptofClyde.Aftermeetingotherelephants,theanalogieswemakebetweenconceptslikeFredandClydeservetopickouttheimportantcharacteristicsofelephants.
Prototypesseemtobebetteratexpressingknowledgeaboutdefaults.Ifweassertgraynessasoneoftheidentifyingcharacteristicsofmembershipinthesetofelephants,wecan'tsaythatthereareexceptionalwhiteelephantswithoutriskingcontradictions.YetitiseasytosaythatFred,thewhiteelephant,isjustlikeClyde,exceptthatheiswhite.AsWittgensteinobserved,itisdifficulttosay,inadvance,exactlywhatcharacteristicsareessentialforaconcept.Itseemsthatasnewexamplesarise,peoplecanalwaysmakenewanalogiestopreviousconceptsthatpreservesomeofthe"defaults"forthatconceptandignoreothers.
3.Inheritanceimplementssets,delegationimplementsprototypes
Havingsetthestagewithourphilosophicaldiscussionoftheissuesofconceptrepresentation,weturnnowtohowtheseissuesaffectthemoremundanedetailsofimplementationofobjectorientedprogrammingsystems.
Implementingthesettheoreticapproachtosharingknowledgeinobjectorientedsystemsistraditionallydonebyamechanismcalledinheritance,firstpioneeredbythelanguageSimula,lateradoptedbySmallTalk,flavorsandLoops,amongothers.Anobjectcalledaclassencodescommonbehaviorforasetofobjects.Aclassalsohasadescriptionofwhatcharacteristicsareallowedtovaryamongmembersoftheset.Classeshavethepowertogenerateinstanceobjects,whichrepresentmembersofaset.Allinstancesofaclasssharethesamebehavior,butcanmaintainuniquevaluesforasetofstatevariablespredeclaredbytheclass.TorepresentClyde,youcreateadescriptionfortheclasselephant,withaninstancevariablefortheelephant'sname,valuesofwhichcanbeusedtodistinguishClydeandFred.Aclasscangiverisetosubclasses,whichaddadditionalvariablesandbehaviortotheclass.
Implementingtheprototypeapproachtosharingknowledgeinobjectorientedsystemsisanalternativemechanismcalleddelegation,appearingintheactorlanguages,andseveralLispbasedobjectorientedsystemssuchasDirector[Kahn79],T[Rees85],Orbit[Steels82],andothers.Delegationremovesthedistinctionbetweenclassesandinstances.Anyobjectcanserveasaprototype.Tocreateanobjectthatsharesknowledgewithaprototype,youconstructanextensionobject,whichhasalistcontainingitsprototypeswhichmaybesharedwithotherobjects,andpersonalbehavioridiosyncratictotheobjectitself.Whenanextensionobjectreceivesamessage,itfirstattemptstorespondtothemessageusingthebehaviorstoredinitspersonalpart.Iftheobject'spersonalcharacteristicsarenotrelevantforansweringthemessage,theobjectforwardsthemessageontotheprototypestoseeifonecanrespondtothemessage.Thisprocessofforwardingiscalleddelegatingthemessage.FredtheelephantwouldbeanextensionobjectthatstoredbehavioruniquetoFredinitspersonalpart,andreferencedtheprototypeClydeinitssharedpart.
4.Toolsforrepresentingbehaviorandinternalstatearethebuildingblocksofobjectorientedsystems
Eachobjectorientedsystemmustprovidesomelinguisticmechanismsfordefiningthebehaviorofobjects.Thephilosophyofobjectorientedprogrammingistousetheobjectrepresentationtoencodeboththeproceduresanddataofconventionallanguages.Ratherthandefinetheproceduralbehaviororthedatacontentofanobjectallatonce,itisconvenienttobreakbothaspectsofanobjectintoasetofpartsthatcanbeaccessedormodifiedindividuallybyname.
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 4/19
Anobject'sinternalstateconsistsofvariablesoracquaintances,whichcanbeaccessedinmostobjectorientedsystemsbysendingtheobjectamessageconsistingofthevariable'sname.Anobject'sprocedureforrespondingtomessages[inactors,wesayitsscript]canbecomposedofasetofprocedurescalledmethods,eachofwhichisspecializedforhandlingonlyacertainsubsetofthemessagestheobjectreceives,identifiedbyname.Breakingupanobject'sstateintonamedvariablesmeansthatdifferentportionsofthestatecanbemodifiedincrementally,withoutaffectingtheothers.Breakingupanobject'sbehaviorintonamedmethodsmeansthatdifferentportionsofthebehaviorcanbemodifiedincrementally,withoutaffectingtheothers.Thelanguagemustthenprovidewaysofcombininggroupsofmethodsandvariablestoformobjectsandsomemeansofallowinganobjecttosharebehavior[implementedasmethodsandvariables]residinginpreviouslydefinedobjects.Wewillcallthesecompositeobjectsextensions.Thesebuildingblocksarerepresentedintheillustration"Toolsforsharingknowledge"with"icons"tobeusedinfurtherdiscussion.
Manyobjectorientedlanguagessupplyprimitivelinguisticmechanismsforcreatingobjectswithmethods,variablesandextensions.Analternativeapproach,whichisadvocatedintheactorformalism,istodefinemethods,variablesandextensionsasobjectsintheirownright,withtheirbehaviordeterminedbyamessagepassingprotocolamongthem.Obviously,anobjectrepresentingamethodcannotitselfhavemethods,otherwiseinfiniterecursionwouldresult.Usingsimpleobjectsprimitivetothesystem,avariableisdefinedtobeanobjectthatremembersanameandavalue,andrespondstoaccessandmodificationmessages.Amethodrespondsonlytothosemessagesforwhichitisdesigned,rejectingothers.Extensionobjectsusedelegationtoforwardmessagesfromonepartoftheobjecttoanothertolocatetheappropriateresponse.
Everyonewhoisalreadyconvincedoftheutilityofobjectorientedprogrammingshouldn'thavemuchtroublediscerningtheadvantagesofusingobjectorientedprogrammingintheimplementationoftheknowledgesharingmechanisms.Foremostamongthemistheabilitytodefineotherkindsofobjectswhichimplementalternativestothestandardversions.Insteadofanordinaryvariable,onemightliketohave"active"variablesthattakeactionwhenchanged,"readonly"variables,maybeeven"writeonly"variables,eachofwhichcouldbedefinedasadifferenttypeofvariableobject.Alternativekindsofmethodobjectscanusedifferingstrategiestocombinebehaviorfromcontributingcomponents,replacingthesocalled"methodcombination"featureoftheflavorssystemandmaking"multipleinheritance"easier.Differentkindsofextensionobjectscanmakedifferentefficiencytradeoffsontheissueofcopyingversussharing.
ToolsforSharingKnowledge
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 5/19
Themechanismsforsharingknowledgeinobjectorientedlanguageshavenowgrownsocomplicatedthatitisimpossibletoreachuniversalconsensusonthebestmechanism.Usingobjectorientedprogrammingitselftoimplementthebasicbuildingblocksofstateandbehavioristhebestapproachforallowingexperimentationandcoexistenceamongcompetingformalisms.
5.ALogoexampleillustratesthedifferencesbetweendelegationandinheritance
AnexamplefromthedomainofLogoturtlegraphicswillillustratehowthechoicebetweendelegationandinheritanceaffectsthecontrolanddatastructuresinanobjectorientedsystem.Thedelegationapproachisillustratedinthefiguretitled"SharingKnowledgewithDelegation".Thefirstthingwewouldliketodoiscreateanobjectrepresentingapen,whichremembersalocationonthescreen,andcanbemovedtoadifferentlocation,drawinglinesbetweentheoldandnewlocations.
SharingKnowledgewithDelegation
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 6/19
Westartoutbycreatingaprototypicalpenobject,whichhasaspecificlocationonthescreenx=200,y=50,andbehaviortorespondtothedrawmessage.Whenwewouldliketocreateanewpenobject,weneedonlydescribewhat'sdifferentaboutthenewpenfromthefirstone,inthiscasethexvariable.Sincetheyisthesameandbehaviorforthedrawmessageisthesame,theseneednotberepeated.
Thedrawmethodwillhavetousethevalueofthexvariable,andit'simportantthatthecorrectvalueofxisused.Whenthedrawmethodisdelegatedfromthenewpentotheoldpen,eventhoughthedrawmethodoftheoriginalpenisinvoked,itshouldbethexofthenewpenthatisused.
Toinsurethis,wheneveramessageisdelegated,itmustalsopassalongtheobjectthatoriginallyreceivedthemessage.ThisiscalledtheSELFvariableinSimula,SmallTalkandflavors,althoughIfindtheterm"self"alittlemisleading,sinceamethodoriginallydefinedforonekindofobjectoftenwindsupsendingtoa"self"ofadifferentkind.Inactorterminology,thisobjectiscalledtheclient,sincetheobjectbeingdelegatedtocanbethoughtofasperformingaservicefortheoriginalobject.Whenapendelegatesadrawmessagetoaprototypicalpen,itissaying"Idon'tknowhowtohandlethedrawmessage.I'dlikeyouansweritformeifyoucan,butifyouhaveanyfurtherquestions,likewhatisthevalueofmyxvariable,orneedanythingdone,youshouldcomebacktomeandask."Ifthemessageisdelegatedfurther,allquestionsaboutthevaluesofvariablesorrequeststoreplytomessagesareallinferredtotheobjectthatdelegatedthemessageinthefirstplace.
Supposenowwe'dliketocreateaturtleatthesamelocationastheoriginalpen,usingtheoriginalpenasaprototype.Howisaturtledifferentfromapen?Aturtlesharessomeofthebehaviorofapen,buthasadditionalstate,namelyit'sheading.Rememberingaheadingisessentialinimplementingtheadditionalbehaviorofbeingabletorespondtoforwardandbackmessagesbyrelyingonthebehavioroftheresponsetothedrawmessage.Wemaychooseeithertoprovideanewbehaviorfortheturtle'sdrawoperation,orrelyonthedrawoperationprovidedbytheoriginalpen.
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 7/19
Let'slookatthesameexamplewiththeinheritanceapproachtosharingknowledgeasfoundinSimulaandSmallTalkinsteadofdelegation.Thisisillustratedinthefiguretitled"Sharingknowledgewithinheritance".Withinheritance,itisnecessarytocreateobjectsrepresentingclasses.Tomakeapen,itisfirstnecessarytomakeapenclassobject,whichspecifiesboththebehaviorandthenamesofvariables.
Individualpensarecreatedbysupplyingvaluesforalltheinstancevariablesofthepenclass,creatinganinstanceobject.Valuesforallthevariablesmustbespecified,eveniftheydonothaveuniquevaluesintheinstance.Nonewbehaviormaybeattachedtoanindividualpen.Extendingbehaviorisaccomplishedbyadifferentoperation,thatofcreatinganewsubclass.Thestepwhichgoesfromaninstancetobehaviorstoredinitsclassisperformedbya"hardwired"lookuploopinsystemslikeSimulaandSmallTalk,notbymessagepassing,asinthedelegationapproach.
Toextendpenswithnewbehavior,wemustfirstcreateanewclassobject.Hereaturtleclassaddsanewheadingalongwithnewbehaviorfortheforwardmessage.Noticethatthevariablesfromthepenclass,xandy,werecopieddownintotheturtleclass.Anindividualturtleinstancemustsupplyvaluesforallthevariablesofitsclass,superclass,andsoon.Thiscopyingleadstolargerinstanceobjectsforclassesfurtherandfurtherdowntheinheritancehierarchy.Thelookupofmethods,performedbyaprimitive,unchangeableroutineinsteadofmessagepassing,startsasearchformethodsintheclassofanobject,andproceedsupthesubclasstosuperclasschain.
Howdoesamethodinheritedfromthepenclasstotheturtleclassaccessamethodimplementedintheturtleclass?Sinceinheritancesystemsusuallydonotusemessagepassingtocommunicatefromsubclasstosuperclass,theycan'tpasstheturtleobjectalonginthemessage,aswewouldindelegation.
SharingKnowledgewithInheritance
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 8/19
Insteadmostusevariablebindingtobindaspecialvariableselftotheobjectthatoriginallyreceivesamessage.Weshallseelateronthatthisleadstotrouble.
Inaddition,inheritancesystemsalsoallowthe"shortcut"ofbindingallthevariablesofaninstancesothattheycanbereferenceddirectlybycodenaminginmethodsasfreevariables.Whilethisissometimesmoreefficient,itshortcircuitsthemessagepassingmechanism,defeatingtheindependenceofinternalrepresentationwhichisthehallmarkofobjectorientedprogramming.Sincevariablereferencesusedifferentlinguisticsyntaxthanmessagesends,ifwewantedtochangethecoordinaterepresentationfromxandytopolarcoordinatesusingrhoandtheta,we'dhavetochangeallthereferencingmethods.Stickingtomessagepassingtoaccessxandymeansthatevenifthecoordinateswerechangedtopolar,wecouldstillprovidemethodsthatcomputetherectangularcoordinatesfromthepolar,andthechangewouldbetransparent.
Ihopethesediagramsleaveyouwiththeimpressionthatthedelegationapproachissimpler.Tocreatetwopensandaturtle,theinheritanceapproachrequirestheadditionalstepsofcreatingpenclassobjectsandturtleclassobjects.Also,wehavetohavetwodifferentkindsoflinksbetweenobjects,thesubclass
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 9/19
linkandtheinstancelink,whereasthedelegationapproachonlyrequiresamessagepassingrelationshipbetweenthelinkedobjects.
6.Areinheritanceanddelegationequallypowerful?
Anobviousquestiontoaskabouttheprecedingdiscussionofinheritanceanddelegationiswhetherthetwotechniqueshavethesameexpressivepower.Theanswerisno.
Givendelegation,itiseasytoseehowwecouldimplementthefunctionalityofinheritance.Wecancreatespecialclassobjectsthatrespondtomessagestocreatenewinstances.Weneedonlyarrangethattheclassobjectsobservethecopyingofvariablesfromthesuperclasschainwhentheycreateinstances.Instanceobjectsaregivenbehaviorthatimplementsthelookupmethods,roughlyasfollows.
IfI'manINSTANCEobject
andIreceiveamessage
withaSELECTORandsomeARGUMENTS:
IftheSELECTORmatches
oneoftheVARIABLEnames
inmyCLASS[orSUPERCLASS,etc.],
Ireturnthecorrespondingvalue,
storedinmyself.
Otherwise,IlookforaMETHOD
whoseNAMEmatches
theSELECTORofthemessage
inthelistoflocalMETHODS
ofmyCLASS.
IfIfindone,
IbindthevariableSELFtomyself
[theINSTANCEobject].
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 10/19
Ibindthenamesof
thevariablesofmyCLASS,
[andallthevariables
uptheSUPERCLASSchain]
totheirvaluesintheINSTANCE.
ThenIinvoketheMETHOD.
Ifthere'snomethod
inmyCLASS'sMETHODlist,
Itrytofindamethod
intheSUPERCLASS,
andsoonuptheSUPERCLASSchain.
Howabouttheotherway?Caninheritanceimplementdelegation?Unfortunatelynot.Thereasonisalittletrickytounderstand,butithastodowiththetreatmentoftheselfvariable,whichpreventsaproperimplementationofforwardingofmessages.
Often,amethodforhandlingamessagemayneedtoasktheobjectthatoriginallyreceivedthemessagetoperformsomeservice.Aturtleobjectwhichreceivesabackmessagewouldliketoturnitintoaforwardmessagesenttothesameobject,butnegatingthenumberofsteps,sothatback100islikeforward100.Indelegation,whenamethodisdelegatedamessage,itreceivesacomponentcalledtheclientinthedelegatemessage,whichhastheobjectthatoriginallyreceivedthemessage.
Ininheritancesystems,adistinguishedvariablenamedselfisautomaticallyboundtotherecipientofamessageduringtheexecutionofcodeforamethod.Whenthemethodsearchproceedsfromtheoriginalclasstoasuperclass,thevalueoftheselfvariabledoesn'tchange,sothatsuperclassmethodscanreplytothemessage"asif"theyweremethodsoftheoriginalobject.However,whenausersendsamessage,theselfvariableisalwaysrebound,sothatitisgenerallynotpossiblefortheusertodesignateanotherobjecttoreplyinplaceoftheobjectwhichoriginallyreceivedthemessage.Truedelegationcannotbeimplementedinthesesystems.
Anexample,illustratedinthefigure"TheSELFProblem,"willmakethisclear.Supposewewouldliketoextendaparticularturtleobjecttocreateaturtlewhichdrawsdashedinsteadofsolidlines.The
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 11/19
obviouswaytodothisistohavethedashedturtleintercepttheforwardmessageandbreakuptheintervalintopieces,delegatingamessagetodrawaseriesofshorterlinestoasolidlineturtle.If,inaninheritancesystem,thedashedlineturtlesimplysendsaforwardmessagetothesolidlineturtle,thenselfwillbeboundtothesolidlineturtle.Ourearlierimplementationofbackintermsofforwardwillthenstopworking,sinceamessagetothedashedlineturtletogobackwilltrytosendaforwardmessagetoselfanddrawasolidlineinstead!
Becarefulaboutconfusingthisexamplewithanalternativeimplementationusinginheritancesystems,whichwouldcreateadashedturtleclassasasubclassofsolidturtleclass.Whilesuchanimplementationcouldhavethecorrectbehaviorwithrespecttothebackmessage,itstillwouldn'tcountasanimplementationofdelegation.Remember,whatweweretryingtodowastoseeifanobjectcouldforwardmessagestosomeotheralreadyexistingobject.Adashedturtleinstancewouldn'tbeforwardinganymessagestoaninstanceofsolidturtle,sinceitwouldjustinheritcopiesofthevariablesandmethodsfromsolidturtle.
7.Whataboutefficiency?
Theefficiencycomparisonbetweendelegationandinheritanceboilsdowntotime/spacetradeoffs.Somehavearguedthatinheritanceismoreefficientbecauseitrequiresfewermessages,butthiscomesatthecostofincreasingthesizeofobjects.Becausevariablesarecopieddownfromsuperclasstosubclass,instancesbecomelargerandlargerthefartherdownyougetintheinheritancehierarchy.Withdelegation,eachobjectneedonlyspecifywhat'sdifferentaboutitfromalreadyexistingprototypes,sothesizeofobjectsdoesnotnecessarilydependonthedepthinthehierarchyofsharedobjects.Alookatthediagramillustratingthedatastructuresforpenandturtleobjectswillconfirminheritance'sspeedadvantageanddelegation'sspaceadvantage.
Smallerobjectsmakeforfasterobjectcreationtimes,whichcanbeimportantinsystemsthatcreatelargenumbersofsmallobjectswithshortlifetimes,asopposedtosmallnumbersoflargeobjectswithlonglifetimes.Reducingthesizeofobjectsmayalsoimprovetheefficiencyofvirtualmemory,byimprovinglocalityofreference,allowingahigherdensityoffrequentlyreferencedobjectsintheprimarymemory.Withacopyinggarbagecollector,suchasthatdescribedin[LiebermanandHewitt83],smallerobjectscanimprovetheefficiencyofgarbagecollectionbyreducingthecopyingoverhead.
Implementorsshouldn'tgetscaredawaybythesearchrequiredtofindmethodsandvariablesinthedelegationapproach.There'sasimple,effectivetrickforreducingthesearchtime:cachingtheresultoflookups.Cachesareawayoftradingspaceforspeed,mitigatinganynegativeeffectsofthespeedforspacetradeoffmadebydelegation.Cachesmakeamoreeffectiveuseoftheextramemorythanindiscriminatelycopyinginstancevariables,becausethememorytheydouseissuretobeinconstantuse.Cachesdon'trestrictflexibilityininteractivelymodifyingtheprogrammingenvironmentthewaycopyingandcompilationoptimizationsdo.
The"SELF"problem
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 12/19
Onconventionalmachines,probablynoimplementationofdelegationisgoingtosurpassvariablelookupviaregistersandstackindexingforrawspeed.Butintheirzealtospeedupvariablelookup,implementorshaveforceddecisionssuchaslargeobjectsizeonobjectorientedlanguages,whichadverselyaffectefficiency.Parallelmachineswithlargeaddressspaceswillmaketheattractivenessofsuchregisterorientedoptimizationsfade.
SmallTalk[Krasner84]reportsa93%"hitrate"foramoderatelysizedcache,1000objects.Thismeansthatanysavingsbyinheritanceoverdelegationinlookupcouldatbestaffecttheremaining7%.Thebestthingtodoseemstobetokeepaglobalcache,andinvalidateitwheneveranychangesaremadetothesharinghierarchy.Achangewillthenslowthesystemdownforthenext1000messages,orwhatevertimethecachetakestofillupagain."Smarter"alternatives,suchasperobjectcachesareprobablynotworththeextratroubletheywouldcauseforincrementalsoftwaremodification,sincethehitrateonaglobalcacheissohigh.Sincebothinheritanceanddelegationcanbeimplementedalmostequallyefficiently,itseemsthatthere'slittlereasontosacrificetheextraflexibilityofdelegationonefficiencygrounds.
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 13/19
8.RedirectingI/Ostreamsillustratesanimportantapplicationofdelegation
Manyobjectorientedsystemsmakegooduseofobjectorientedprogrammingtechniquestoimplementinputoutputstreams.Suchastreamisanobjectthatreceivesmessagestoinputoroutputacharacter,alineoftext,anexpression.Systemsusuallyhaveglobalvariablesdesignatingthe"current"sourcesofinputandoutput,whichisbydefaultboundtoanobjectrepresentingthestreamofcharactersbeingdisplayedonthewindowofascreenofaninteractivedisplay.
Thename"stream"suggeststhecontinualflowofcharactersorpixelsbetweentheuserandthesystem.Averyusefulkindofobjectisthatwhichimplementsa"dam"todivertthestreamtootherdestinations,or"plumbing"whichconnectsonestreamwithanother.Adribblefileisasequentialfilemaintainingarecordondiskofthehistoryofinputoutputinteractions,toprovideamorepermanentrecordingofinteractionsthantheephemeraltwinklingofpixels.Adribblefilecanbeimplementedbyreplacingthestreamwhichrepresentsinteractionsattheterminalwithonethatwritesthemtodiskalso.
Thedribblestreamneedstheabilitytomasqueradeastheterminalstream.Itshouldhavethesameresponsestoallthemessagesthattheordinaryterminalstreamhas,andalsoprovidetheadditionalbehaviorofwritingtothedisk.Thestreamsshouldbeconsideredindistinguishablefromthepointofviewofallprogramswhichperforminputoutput.
Toimplementthedribblestreamcleanly,we'dlikeittobethecasethattheimplementationofthedribblestreamshouldn'thavetoknowtheprecisedetailsoftheimplementationofthestreamwhichitisreplacing.Wemight,forexample,liketouseasingledribblestreamwithbothastreamtoadirectlyconnectedinteractiveterminalandastreaminteractingoveranetwork.
Canadribblestream"masquerade"asaterminalstream?
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 14/19
Theimplementationusingdelegationisconvenientandstraightforward.Messageswhichdocharacteroutputareinterceptedandthediskoutputisinterposed.
ADRIBBLESTREAMisanobject
thatlogsinteractiononaSTREAM,
andrecordsitondiskusingaFILE
NAME
IfI'maDRIBBLESTREAMand
Igetamassagetoinputoroutput
aCHARACTER,
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 15/19
IoutputtheCHARACTER
tothediskstreamtotheFILE
NAME.
ThenIdelegatethemessage
tooutputaCHARACTER
totheoriginalSTREAM.
IfI'maDRIBBLESTREAMand
Igetanyothermessage,
Isimplydelegatethemessage
totheSTREAM.
Itworkstotakecareofonlythesinglecharacterinputandoutputmessagesbecausepresumablyallhigherlevelmessages,likeprintofanobject,areultimatelyimplementedintermsofthesinglecharacterversions.Themethodwhichperformsahigherlevelprintoperationwouldultimatelysendacharacteroutputmessagetoitsclient[sendtoself].
Surprisingly,manyinheritancesystemsmakeitdifficulttoimplementthissimpleextensiontothebehaviorofstreams.OnevillainistheinsistenceofsystemslikeflavorsandSmallTalkondefiningseparateproceduresforhandlingeachtypeofmessage.Attemptingtotrytoimplementdribblestreamasasubclassofstreaminsystemsofthisilk,wewouldfindthatthere'snoeasywaytosay"...andsendalloftheirrelevantmessagesthroughtotheoriginalstream".Wewouldbeforcedtodefineonemethodtointerceptthecharacteroutputmessagetowritetothedisk,anothertointercepttheprintmessage,anothertointercepttheprintlinemessage,andsoonforeveryrelevantmessage.Everytimeanothermessagewasaddedtotheoriginalstreamanothermethodwouldhavetobeaddedtothedribblestream,withtediouslyrepetitivecode.Thisalsohastheunfortunateeffectofmakingtheimplementationofdribblestreamnowsensitivetothedetailsofexactlywhichmessagesitsembeddedstreamaccepts,inhibitingtheabilitytoreusetheimplementationwithdifferenttypesofstreams.
Addingtothesystemthedefinitionofadribblestreamclassorflavorwouldonlygivetheabilitytocreatenewinstancesofdribblestreamobjects.Itwouldnotbepossibletocreateadribblestreamwhichusedapreviouslyexistingstreamobject.We'dthenhavetomakenewterminalstreams,networkstreams,orotherkindofstreams,tobeabletotakeadvantageoftherecordingfunctionality.Weshouldn'thavetoreproduceeverykindofstreaminthesystemjusttohavethedribblecapability!
If,instead,weattempttomakeadribblestreamwhichholdstheinteractionstreamasoneofitsinstancevariables,wefacetheproblemthatthereisnowayforthedribblestreamtocorrectlyforwardamessagelikeprinttothevalueofthevariable.Becauseofthewaythesesystemshandletheselfvariable,the
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 16/19
forwardingofmessagestotheoriginalstreamwon'twork,forthesamereasonasintheturtleexample.Sendingaprintmessagetotheinstancevariablewouldrebindtheselfvariable,soitwouldresultinsendinglowerlevelmessagesdirectlytotheinteractionstreamandnottothedribblestream.Soitseemsasthoughanystraightforwardattempttoimplementthedribblestreamasasimplebehavioralextensioninmanyinheritancesystemsisdoomed.
9.ParallelismcausesproblemsininheritancesystemsbecauseoftheSELFvariable
There'sanadditionalprobleminthecasethatthestreamcanacceptmessagesfrommorethanoneparallelprocess.Becausethestreamholdsmodifiablestate[suchasascreenbitmap],thestreammustbeprotectedagainsttimingerrorsresultingfromtwoprocessestryingtowritetothestreamatthesametime.Atechniquesuchasserializerobjects[Hewitt,Attardi,Lieberman79]ormonitorsmustbeused.Thismeansthatwhenthestreamreceivesawritemessage,it"locks",sothatsubsequentmessagestothestreammustwaitinaqueueforthestreamtofinishprocessingthefirstwritemessage.
Now,ifamessagetoadribblestreamtriestoprocessaprintmessagebysendingacharacteroutputmessagetotheselfvariable,itwillfindselfboundtoastreamwhichislockedwaitingforthatveryprintmessagetocomplete!Deadlock!
Sincedelegationusesmessagepassing,whenthedribblestreamdelegatestoaterminalsystemitcansupply[astheclientinthedelegatemessage]anunserializedversionofitself,whichcanprocessthemessagewithoutwaiting.
10.Delegationismoreflexiblethaninheritanceforcombiningbehaviorfrommultiplesources
Often,anobjectwillwanttoutilizebehaviorthatappearsinmorethanoneotheralreadyexistingobject.Thebehaviorthatasystemneedstoimplementaparticular"feature"canbepackagedupasasingleobject,andsometimesanobjectwillwanttocombineseveralofthesefeaturestoimplementitsbehavior.Forexample,windowobjectsmighthavetitles,borders,sizeadjustments,etc.Aparticularwindowobjectmaychoosesomeofthesefeaturesandnotothers.Featuresmaybeindependentofoneanother,ortheymayinteract.
Thesolutionininheritancesystemsistocreateaclassobjectthatmentionsalistofotherclasseswhosebehavioritwishestosham.Allthemethodsandvariablesmentionedinanyoftheclassesareinheritedbythecombinedobject.Systemslikeflavorsallowoptionally,onapermethodbasis,supplyinganoptionforhowtocombinebehaviorwhenmorethanonecomponentcontributesamethod.Typicaloptionsaretoinvokeallthecontributingmethods,imposeanorderonthem,orreturnalistoftheresults.
Theproblemwiththisstyleofcombiningbehaviorfrommultiplesourcesisthatitfixesthepatternofcommunicationbetweenobjectsbeforethetimeaninstanceobjectiscreated.Thislimitstheextenttowhichbehaviorfrompreviouslyexistingobjectscanbeuseddynamically.Bycontrast,withdelegation,thecommunicationpatternscanbedeterminedatthetimeamessageisreceivedbyanobject.
Withdelegation,amethodforanextensionobjectcansimplyaccesstheprototypicalobjectsfromwhichitderivesbehavioronthesharedlist.Awindowwhichwantstoinvokethedrawactionofapreviouslydefinedrectangleobjectactingasitsborderscansimplydelegatethedrawmessagetotherectangleobject.Thusdelegationdoesn'trequire"methodcombination"oraninventoryofesotericcombiningoperations.Thebehaviorissimplyprogrammedinthemethodforthecombinedextensionobject.Shouldaprogrammerwishtobuildalibraryofcommoncombinationtechniques,itiseasilydonebyconstructingvariantsonthestandardmethodobject,sodelegationcouldbemadeasconciseasmethodcombinationininheritancesystems.Withinheritance,ifawindowclassincludesa"bordersmixin",the
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 17/19
windowdoesnotcontainanindependentobjectrepresentingitsborders,soitisnotpossibletosendamessagetothebordersofawindowindependentofthewindowobjectitself.Thewindowclassmerelycontainsamixtureofthemethodsandvariablesinheritedfromthebordersandothercontributingcomponents.
Inhighlyresponsiveinteractivesystems,itisoftennecessarytowaituntilamessageisreceivedtodeterminehowbehaviorfromcomponentobjectswillbeutilized.Here'sasimpleexampleinwhichdynamicutilizationofbehaviorfrommultiplesourcesisrequired,illustratedinthefigure"Delegationallowscommunicationpatternstobedecidedatruntime".
Aborderedbitmapcanbebuiltfromarectangle,whichcandisplayitsborders,andabitmapwhichcantransferanarrayofpixelstothescreen.Whatshouldthedrawresponsefortheborderedbitmapbe?Withinheritanceyoucreateaborderedbitmapclassthatinheritsbothfromrectangleandbitmap,sayingthatbothdrawmethodsaretobeused.Fine.
Butnowsupposewe'dliketogivetheusertheoptionofchangingdynamicallywhichbehaviorisused.Whenthebitmapisdraggedacrossthescreen,thetransferoftheentirearrayoneverymousemovementmightbetooslow,soitmightbepreferabletogivetheusertheoptionofjustdraggingtheoutlineofthebitmapinstead.Areasonablethingtodoistogivetheuseranonscreentoggleswitchtodecidethebehavior,andtheusercanpotentiallychangethebehavioratanytime.Sothebehavioroftheborderedbitmapcannotbedecidedbeforetheobjectiscreated.Withdelegation,whentheborderedbitmapgetsadrawmessage,itcandecidewhethertodelegatethemessagetotherectangleobjectthatitcontains,ortothebitmapobject,orboth.
Delegationallowscommunicationpatternstobedecidedatruntime
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 18/19
InheritancesystemsarealsoplaguedbywhatIcalltheoneinstanceclassproblem.Whensystemsarecomposedoflargenumbersofobjectswithslightlyvaryingbehavior,youwinduphavingtocreatenewclassobjectsoftenjusttohaveoneorafewinstances.Itisnecessarytocreateadhocclassessuchas"windowwithawideborder,timesromanfontandnotitle"justtocombinefeaturesforasingleinstance.
11.Delegationisadvantageousforhighlyinteractive,incrementalsoftwaredevelopment
Animportantissuetoconsiderwhenevaluatingthetradeoffsbetweeninheritanceanddelegationistheconsequencesforincrementalsoftwaredevelopment.Aswehaveseenabove,inheritancetendstoencouragecopyingofvariablesandmethods,whiledelegationencouragessharing.Ifaprototypicalobjectchangesbehavior,thenallobjectswhichmentionthatprototypeontheirsharedlistwillautomatically"feel"thechange.Ifchangesaremadetoaninheritancehierarchy,suchasaddinganewinstancevariable,orchangingtheclassstructure,informationcopiedfromtheolddatastructuremayberenderedobsolete.Broadcastingtheresultofchangestocopiesputsaburdenontheoperationswhichmakeincrementalchangesinthesoftwareenvironment.Anextremeexampleofthisoccursintheflavorssystemwheresimplyaddingamethodtovanillaflavor,therootoftheinheritancehierarchy,resultsinrecompilationofeveryflavorintheentiresystem!Thiseffectivelyprohibitsanymodificationstoobjectsnearthetopoftheinheritancehierarchy.
Thoughdelegationhasbeentheminorityviewpointinobjectorientedlanguages,itisslowlybecomingrecognizedasimportantforitsaddedpowerandflexibility.Partofthereasonforneglectofthedelegationapproachhasbeenhistorical.Simula,oneofthefirstobjectorientedlanguages,adoptedtheinheritancetechnique.Itfixedcommunicationpatternsbetweenobjectsatcompiletime,aswasappropriateforacompiledlanguageoftheAlgolfamily.Thespecificmechanismsforthiswerethen"inherited"bySmallTalkandothers,withoutreconsideringwhethertheapproachwasstillappropriateforaninterpretivelanguageinamorehighlyinteractiveprogrammingenvironment.Ihopetheprecedingdiscussionhasconvincedyouthattheapproachofmodelingconceptsusingprototypesandimplementingbehaviorinobjectorientedlanguagesusingdelegationhasdistinctadvantagesoverthealternativepointofviewusingclassesandinheritance.
12.Acknowledgments
MajorsupportfortheworkdescribedinthispaperwasprovidedbytheSystemDevelopmentFoundation.OtherrelatedworkattheMITArtificialIntelligenceLaboratorywassupportedinpartbyDARPAunderONRcontractN0001480C0505.
CarlHewitt'sideasconcerningactors,andespeciallytheimpactofparallelismonobjectorientedprogrammingwereimportantinfluences.KennethKahnandLucSteelsimplementedobjectorientedlanguageswhichadopteddelegationmechanismsandalsoinfluencedtheseideas.AlanBorningreachedsimilarconclusionsinthecontextoftheThingLabsystemimplementedinSmallTalk.KoendeSmedtprovidedahelpfulcritiqueofatalkIgaveontheseissuesinNijmegen,theNetherlands.
References
[Birtwistle,Dahl,Myhrhaug,andNygaard73]G.M.Birtwistle,OJDahl,B.Myhrhaug,K.Nygaard.SimulaBegin.VanNostrandReinhold,NewYork,1973.
[Bobrow85]D.Bobrow,K.Kahn,M.Stefik,G.Kiczales.CommonLoops.TechnicalReport,XeroxPaloAltoResearchCenter,1985.
[Bobrow,Stefik83]DanielBobrowandMarkStefik.KnowledgeProgramminginLoops.AlMagazine,August,1983.
-
01/04/2015 Untitled
http://web.media.mit.edu/~lieber/Lieberary/OOP/Delegation/Delegation.html 19/19
[Borning86]AlanBorning.ClassesVenusPrototypesinObjectOrientedLanguages.InFallJointComputerConference.ACM/IEEE,Dallas,Texas,November,1986.
[Goldberg,Robson83]AdeleGoldbergandDavidRobson.SmallTalk80:TheLanguageanditsImplementation.AddisonWesley,Reading,MA,1983.
[Hewitt79]CarlHewitt.ViewingControlStructuresasPatternsofPassingMessages.InP.WinstonandR.Brown[eds.],ArtificialIntelligence,anMITPerspective.MITPress,Cambridge,MA,1979.
[Hewitt,Attardi,Lieberman79]CarlHewitt,GiuseppeAttardi,andHenryLieberman.SecurityAndModularityInMessagePassing.InFirstConferenceonDistributedComputing.IEEE,Huntsville,1979.
[Kahn79]KennethKahn.CreationofComputerAnimationfromStoryDescriptions.Ph.D.thesis,MassachusettsInstituteofTechnology,1979.
[Krasner84]GlennKrasner,editor.SmallTalk80:BitsofHistoryandWordsofAdvice.AddisonWesley,NewYork,1984.
[Lieberman86a]HenryLieberman.ConcurrentObjectOrientedProgramminginAct1.InA.YonezawaandTokoro[eds.],ConcurrentObjectOrientedProgramming.NUTPress,Cambridge,MA,1986.
[Lieberman86b]HenryLieberman.DelegationandInheritance:TwoMechanismsforSharingKnowledgeinObjectOrientedSystems.InJ.Bezivin,P.Cointe[eds.],3emeJourneesd'EtudesLanguagesOrientesObjets.AFCET,Paris,France,1986.
[LiebermanandHewitt83]HenryLiebermanandCarlHewitt.ARealTimeGarbageCollectorBasedontheLifetimesofObjects.CACM26(6),June,1983.
[Moon,Weinreb84]DavidMoon,DanielWeinreb,etal.LispMachineManual.Symbolics,Inc.andMIT,Cambridge,MA,1994.
[Rees85]JonathanRees,etal.TheTManual.TechnicalReport,YaleUniversity,1985.
[Steels82]LucSteels.AnApplicativeViewofObjectOrientedProgramming.TechnicalReportAlMemo15,SchlumbergerDollResearch,March,1982.