您好,欢迎来到易妖游戏网。
搜索
您的当前位置:首页Abstract International Workshop on Aliasing, Confinement and Ownership in object-oriented p

Abstract International Workshop on Aliasing, Confinement and Ownership in object-oriented p

来源:易妖游戏网
InternationalWorkshoponAliasing,ConfinementandOwnershipinobject-orientedprogramming(IWACO)2007

OwnershipDomainsintheRealWorld

MarwanAbi-Antoun

SchoolofComputerScienceCarnegieMellonUniversitymarwan.abi-antoun@cs.cmu.edu

Abstract

TheOwnershipDomainstypesystemhashadpubliclyavailabletoolsupportforafewyears.However,thepreviousimplementationusednon-backwardscompatiblelanguageextensionstoJavaandranonaresearchinfrastructure,whichmadeitdifficulttoconductsubstantialcasestudiesoninterestingsystems.

Wefirstpresentare-implementationofownershipdomainsus-ingJava1.5annotationsandtheEclipseinfrastructure.Wethenusetheimprovedtooltoannotatetworeal15,000-lineJavaprogramswhileusingrefactoringtoolsupport,genericsandexternallibraries.Ownershipdomains,asmostotherownershiptypesystems,provideusefulencapsulationproperties.Weillustrateusingactualexamplesfromthesubjectsystemshowownershipdomainsalsoexpressandenforcedesignintentregardingobjectencapsulationandcommunicationandhelpidentifytightcoupling.Finally,wementionsomeexpressivenessgapsthatweencountered.

1.Introduction

Researchershaveproposedmanyownershiptypesystems,e.g.,[15,10,3,17,41],buthavenotreportedsignificantexperiencewithmostofthemonrealcode.Onlyafewsystems,notablyOwnershipDomains[6,3],Universes[17]andGenericOwnership[41],havereleasedtoolsupport[46,20,40],andevenfewersystemshavebeenevaluatedinsubstantialcasestudies[6,25,2,38].

Thepreviousimplementationofownershipdomains[3]usednon-backwardscompatibleextensionsofJava[46].Asaresult,noneoftherichtoolsupportforJavaprogramswasavailabletoprogramswithownershipdomainannotations1.

Inapreviouscasestudy[2],weidentifiedthataddingowner-shipdomainannotationstoexistingcodeoftenhighlightsrefactor-ingopportunities.Forinstance,alengthydomainparameterlistisoftenanindicationoftightlycoupledcodethatcouldbenefitfromrefactoring—suchasextractinganinterfaceandprogrammingtothatinterface.Itisunrealistictoassumethatitispossibletorefactorallsuchcodepriortoannotatingit.Inourexperience,havingac-cesstorefactoringtoolsupportduringtheannotationprocesswasinvaluable.Usinglanguageextensionsalsomakesithardertopar-tiallyandincrementallyannotateexistingcodeandthusconductcasestudiesoninterestingsystems.Finally,theprevioustoolusedamodifiedresearchinfrastructure[8]thatisnolongeractivelymain-tainedanddoesnotsupportJavagenerics—asofthiswriting.Toaddresstheseadoptabilitychallenges,were-implementedtheOwnershipDomainstypesystemusingtheannotationfacilityinJava1.5[27],sothatJavaprogramswithownershipannotationsremainlegalJava1.5programs.WealsoimplementedthetoolasaplugintotheEclipseopensourcedevelopmentenvironmentthathasbecomepopularwithresearchersandpractitioners[24,37].

1The

UniversestoolsbuiltontheJavaModelingLanguage(JML)infras-tructuresupportbothlanguageextensionsandstylizedcomments[20].1JonathanAldrich

SchoolofComputerScienceCarnegieMellonUniversityjonathan.aldrich@cs.cmu.edu

WebelievethisimprovedtoolsupportpromotestheadoptabilityoftheownershipdomainstechniquebyJavadevelopersasfollows.First,alltheEclipsetoolsupportsuchassyntaxhighlighting,refac-toring,etc.,remainsavailabletoannotatedprograms.Second,usingannotationsmakesiteasiertosupportinanon-breakingwayad-ditionalannotationssuchasexternaluniqueness[14]orreadonly[17].Third,usingannotationsgivestheabilitytoincrementallyandpartiallyspecifyannotationsonlargecodebases.Fourth,usingan-notationswillmakeitpossibletostudytheevolutionofprogramswithownershipannotations,anareathathasnotreceivedmuchattention—sincenoonewillmaintainaprogramwithlimitedtoolsupport.Finally,annotatingexistingcodeisdifficultandtime-consumingandtoolsarebeingdevelopedtoaddannotationssemi-automatically[6,16].Oneofthebenefitsofusingannotationsoverlanguageextensionsisthataninferencealgorithmcannotbreakanexistingprogrambyinsertingpotentiallyincorrectannotations.Wemadethefollowingdesignchoicesfortheannotationsys-tem.First,weworkedwithinthelimitsofJava1.5annotations[27],eventhoughannotationsmaybemoreverbosethananele-gantlydesignedlanguage.Moreover,Java1.5annotationsimposeseveralrestrictions,e.g.,noannotationsongenerictypearguments.Otherresearchershavetriedtoeliminatesomeoftheserestrictionsbyproposingrevisionsofthelanguage[19],butuntilsuchpropos-alsareofficiallyadopted,theirprototypeimplementationsarenotEclipsecompatible,animportantfactorforadoptability.Second,toworkaroundtheJava1.5limitationofallowingannotationsonlyondeclarations,weconsistentlydeclareadditionaltemporaryvari-ablesandaddannotationstothem.Thishasworkedwellfornewexpressions,castexpressions(bothimplicitandexplicit)andar-gumentsformethodandconstructors.Third,checkingownershipdomainannotationsonlygeneratesinformationalmessages,i.e.,noerrorsorwarnings,anddoesnotstopadeveloperfromrunningtheprogram.Fourth,wehard-codeaminimalnumberofimplicitdefaultsandprovideaseparatetooltosupplyexplicitreasonabledefaultstoreducetheannotationburden.Inthefuture,thistoolcanbereplacedwithasmarterannotationinferencetool.Finally,theannotations2arenon-executableanddonotaffecttheprogram’sbe-havior;unliketheearlierimplementation,thecurrentsystemdoesnotincluderuntimechecks.Asaresult,theannotation-basedsys-temisunsoundatcasts—butcouldbemadesoundusingbytecoderewritingtoaddnecessarydynamicchecks.

Therestofthepaperisorganizedasfollows:wereviewowner-shipdomainsinSection2,describetheannotationlanguageinSec-tion3andthesalienttoolfeaturesinSection4.WediscusstwocasestudiesinSection5andshowhowownershipdomainsexpressandenforcedesignintentrelatedtoobjectcommunicationandencap-sulation.WediscusssomeexpressivenessgapsthatweencounteredinSection6andconcludewithrelatedworkinSection7.

2Annotations

mayincreasethememoryfootprintandslowdownclass

loadingasaresult,butnoempiricaldatahasbeenreportedtodate.

2007/7/3

2.ReviewofOwnershipDomains

Ownershipdomainsareconceptualgroupsofobjectswithexplicitdomainnamesandexplicitpoliciesthatgovernreferencesbetweenthem.Eachobjectbelongstoasingleownershipdomain,andatop-leveldomainisassumed.

PublicandPrivateDomains.Eachobjectcandeclareoneormorepublicorprivatedomainstoholditsinternalobjects,thussupportinghierarchy.Apublicdomainisaccessedusingasyntaxsimilartofieldaccess.Domaindeclarationsareaddedtoaclass,butforeachinstanceofthatclass,freshinstancesofthesedomainsarecreatedforthatobject,i.e.,obj1.DomainAandobj2.DomainAaredistinctifobj1andobj2areinstancesofthesameclassTanddonotaliaseachother.

ExplicitDomainLinks.Eachobjectcandeclareapolicyde-scribingthepermittedaliasingamongobjectsinitspublicdomains,andbetweenitsprivatedomainsandpublicdomains.Ownershipdomainssupporttwokindsofpolicyspecifications:a)alinkfromonedomaintoanotherallowsobjectsinthefirstdomaintoaccessobjectsintheseconddomain;andb)permissiontoaccessanobjectimpliespermissiontoaccessitspublicdomains.Inadditiontoex-plicitdomainlinks,thefollowingimplicitpolicyspecificationsareincluded:a)anobjecthaspermissiontoaccessotherobjectsinthesamedomain;andb)anobjecthaspermissiontoaccessobjectsinanydomainthatitdeclares.Anyreferencenotexplicitlypermittedbytheserulesisprohibited,andlinkpermissionsarenottransitive.OwnershipDomainParameters.Twoobjectscanaccessob-jectsinthesamedomain,aslongasimplicitorexplicitpermissionsallowthataccess,bydeclaringaformaldomainparameterononeobject,andbindingthatformaldomainparametertoanotherdo-main.Methoddomainparametersarealsosupportedandareoftenneededforstaticmethods.

AliasTypes.Inaddition,thefollowingspecialannotationsaredefinedforincreasedexpressiveness[3]:

•unique:indicatesanobjecttowhichthereisonlyonerefer-encesuchasanewlycreatedobject.Uniqueobjectscanbepassedlinearlyfromoneobjecttoanother,bydestroyingtheoldreferencetotheobjectwhenthenewreferenceiscreated;•lent:oneownershipdomaincantemporarilylendanobjecttoanotherownershipdomain,withtheconstraintthatthesecondownershipdomainwillnotcreateanypersistentreferencestothatobject:e.g.,amethodformalparameterisoftenannotatedwithlenttoindicatethatitisatemporaryalias;

•shared:indicatesthatanobjectmaybealiasedglobally.sharedreferencesmaynotaliasnon-sharedreferences.

Unlikeowner-as-dominatortypesystems[15],publicdomainsintheownershipdomainstypesystemcanexpressconstructssuchasiterators[3](SeeFigure1)oraninstanceoftheCompos-itedesignpattern[22,p.163]thatdoesnotencapsulateitssub-componentsandgivesclientstheabilitytoaddcomponentstoanycompositeofthehierarchyandnotonlytotherootcomposite[30].Developerscanstillexpressowner-as-dominatorinownershipdo-mainsby:a)neverdeclaringapublicdomain;andb)neverlinkingadomainparametertoaninternaldomain[3].

3.AnnotationDesign

Inthissection,wedescribetheconcreteannotationsyntax.FormaximumflexibilityandtoworkaroundsomeofthelimitationsofJava1.5annotations,allannotationvaluesarestrings.Annotationsthatarepluraltakevaluesthatarearraysofstrings.

TheannotationsareillustratedusingsnippetsfromacanonicalSequenceabstractdatatype,acommonbenchmarkforownershiptypesystems.WithintheSequence,theitersownershipdomainisusedtoholdIteratorobjectsthatclientsusetotraversetheSequence,andthedefaultprivateownedownershipdomainis

2

usedtoholdtheConscellsinthelinkedlistthatisusedtorepresenttheSequence.ThefullexampleisshowninFigure1.@Domains:declarepublicorprivatedomainsonatype.•Format:identifier

•Appliesto:type(classorinterface).

•Examples:thefollowingdeclaresaprivateowneddomain(ownedisprivatebynamingconvention),andapublicdomainiterstostoretheIteratorobjectsoftheSequence.

@Domains({\"owned\",\"iters\"})classSequence{...}

@DomainParams:declareordereddomainparametersonatypeormethoddomainparametersonamethod.•Format:identifier

•Appliesto:typeormethod.

•Examples:SequencedeclaresadomainparameterTownertoholditselements.

@DomainParams({\"Towner\"})classSequence{...}

@DomainInherits:passparameterstosuperclassorimplementedinterfaces.

•Format:typename•Appliesto:type(classorinterface).

•Examples:theIteratorinterfaceisalsoparameterizedbytheTownerdomainparameter.ClassSeqIteratorinheritsdomainparameterTownerfrominterfaceIterator,andaddsthelistparametertoaccesstheConscells.

@DomainParams({\"list\",\"Towner\"})

@DomainInherits({\"Iterator\"})

classSeqIteratorimplementsIterator{...}

@DomainLinks:declaredomainlinks.

•Format:fromDomainId->toDomainId•Appliesto:type(classorinterface).

•Examples:theSequencegivesIteratorobjectsintheitersdomainpermissiontoaccessobjectsintheowneddomain,includingtheConscells.

@DomainLinks({...,\"iters->owned\",...})classSequence{...}

@DomainAssumes:declaredomainlinkassumptions.•Format:fromDomainId->toDomainIds•Appliesto:type(classorinterface).

•Examples:theSequenceassumesthattheowneroftheSequencehasaccesstotheTownerdomaincontainingthesequenceelements.

@DomainAssumes(\"owner->Towner\")/∗default∗/classSequence{...}

@Domain:declarethedomain,actualparametersandactualarrayparameters.

•Format:annotation[arrayParams,...]

annotation:indicateadomainname(e.g.,owned),oneofthespecialaliastypes(e.g.,unique),orapublicdomainofanobjectusingafieldaccesssyntax(e.g.,seq.iters);:specifyactualdomainparametersbyorderofformaldomainparameters,atobjectcreationandaccesssites;

2007/7/3

[arrayParams,...]:inownershipdomains,arrayshavetwoownershipmodifiers,oneforthearrayobjectitselfandonefortheobjectsstoredinthearray.Forvariablesofarraytype,thisargumentspecifiestheactualarrayparametersbyorderofarraydimension(formulti-dimensionalarrays).Appliesto:localvariabledeclaration,fielddeclaration,methodformalparameterandmethodreturnvalue.

Examples:thefollowingdeclaresauniqueIteratorob-jectandbindsthelistdomainparameteronSeqIteratortoowneddomainonSequence,andtheTownerdomainparameteronSeqIteratortotheparameterbythesamenameonSequence.

@Domain(\"unique\")

SeqIteratorit=newSeqIterator(head);

Examples:alentarrayofsharedStrings:

@Domain(\"lent[shared]\")Stringargs[];

@DomainReceiver:declarethedomainofthereceiverofacon-structororamethod.•Format:identifier

•Appliesto:constructorormethod.•Examples:

@DomainReceiver(\"state\")voidrun(){...}

4.ToolDesignandImplementation

OwnershipdomainannotationsaretypecheckedusingtwovisitorsontheEclipseAbstractSyntaxTree(AST).4.1

OwnershipDomainsTypechecking

Afirst-passvisitorperformsthefollowing:

•IdentifyProblematicPatterns:thesewillneedtobereplacedwithequivalentconstructs,e.g.,bydeclaringalocalvariableandaddingtheappropriateannotationstoit;3

•ReadAnnotationsfromAST:theJava1.5annotationsaddedtoaprogramarepartoftheAST.Thevisitorlocatesthean-notationsnodesintheASTandparsestheircontentsusingaJavaCC[26]parser.Thevisitoralsolocatesspecialblockcom-mentsonmethodinvocationexpressionsasdescribedlater.Inaddition,thevisitorinfersdefaultannotationsforsomeASTnodesthatcannotbeannotated,e.g.,itimplicitlydefaultstheNullLiteralASTnodetounique.ThevisitormapseachASTnodetoanannotationstructureinpreparationforthesec-ondpassvisitorwhichwilltypechecktheannotations;

•PropagateLocalAnnotations:thevisitorpropagatestheex-plicitannotationsfromtheASTnodes(fortypes,variables,andmethods)toalltheexpressionnodesintheAST,includ-ingtranslatingformalstoactuals.

Asecond-passvisitorcheckstheannotationsoneachexpressionbasedonthestaticsemanticsofOwnershipDomains.Checkingtheassignmentrulerequiresavalueflowanalysis.ALiveVariablesAnalysis(LVA)fromalightweightdataflowanalysisframework[5]—thatalsousestheEclipseAST,isinvokedintra-procedurallyateachmethodboundaryusingaseparatevisitor.TheLVAanalysisverifiesthatauniquepointeronlyhasonenon-lentread.4.2

AdditionalFeatures

Thetooloffersthefollowingadditionalfeatures:

3Using

theEclipsebuilt-inrefactoring(“ExtractLocalVariable”),this

operationcanbeperformedwithverylittleeffort.

3@Domains({\"owned\",\"iters\"})@DomainParams({\"Towner\"})

@DomainAssumes(\"owner->Towner\")

@DomainLinks({\"owned->Towner\",\"iters->Towner\",

\"iters->owned\"})

classSequence{

@Domain(\"owned\")Conshead;voidadd(@Domain(\"Towner\")To){@Domain(\"owned\")

Conscons=newCons(o,head);head=cons;}

@Domain(\"iters\")IteratorgetIter(){@Domain(\"iters\")

SeqIteratorit=newSeqIterator(head);returnit;}}

@DomainParams({\"Towner\"})

@DomainAssumes(\"owner->Towner\")classCons{

@Domain(\"Towner\")Tobj;

@Domain(\"owner\")Consnext;Cons(@Domain(\"Towner\")Tobj,

@Domain(\"owner\")Consnext){this.obj=obj;this.next=next;}}

@DomainParams({\"Towner\"})interfaceIterator{

@Domain(\"Towner\")Tnext();booleanhasNext();}

@DomainParams({\"list\",\"Towner\"})@DomainAssumes({\"list->Towner\"})

@DomainInherits({\"Iterator\"})

classSeqIteratorimplementsIterator{@Domain(\"list\")Conscurrent;...

SeqIterator(@Domain(\"list\")Conshead){current=head;}

public@Domain(\"Towner\")Tnext(){

@Domain(\"Towner\")Tobj2=current.obj;current=current.next;returnobj2;}}

@Domains({\"owned\",\"state\"})classSequenceClient{

final@Domain(\"owned\")

Sequenceseq=newSequence();voidrun(){

@Domain(\"state\")Integerint5=newInteger(5);seq.add(int5);

@Domain(\"seq.iters\")

Iteratorit=this.seq.getIter();while(it.hasNext()){

@Domain(\"state\")Integercur=it.next();...}}...}

Figure1.ASequenceAbstractDataTypewithownershipdo-mainannotations.

2007/7/3

@DomainParams({\"state\"})classStudent{...}

@DomainParams({\"state\"})classData...{

final@Domain(\"state>\")SequencevStudent;

@Domain(\"state\")Student

getStudentRecord(@Domain(\"shared\")StringsSID){@Domain(\"vStudent.iters>\")Iteratori=vStudent.getIter();while(i.hasNext()){

@Domain(\"state\")

StudentobjStudent=i.next();...}...}}

Figure2.Addingannotationstogenericcode.

ExternalLibraries.TherearetwoapproachestosupportaddingannotationstothestandardJavalibrariesandotherthird-partylibraries,onethatinvolvesannotatingthelibraryandpoint-ingthetooltotheannotatedlibraryandonethatinvolvesplacingtheannotationsinexternalfiles.Theearliertoolusedtheformerapproach[46],butweadoptedthelatterapproachthistimesinceitdoesnotrequirechanginglibraryorthird-partycode—whichmaynotbeavailableandwhenitis,tendstoevolveseparately.Otherannotationbasedsystemsadoptedthesamestrategy[42].ThetoolsupportsassociatingownershipdomainannotationswithanyJavabytecode.classfileusinganexternalXMLfile,followingthesameannotationconstructsdescribedinSection3.

Generics.Ourannotationsystemcurrentlytreatgenerictypesasorthogonaltoownershipdomainparameters,sogenerictypepa-rametersandargumentsareaddedseparatelyfromownershipdo-mainannotations—exceptthatnestedactualdomainsmayneedtobeprovidedwhereapplicable.ProponentsofGenericOwner-ship[41]arguethatthisleadstoawkwardsyntax,whichmaybetrue.However,inourcasestudiesannotatingtwo15,000-lineJavaprogramsincludingusinggenerictypes,wedidnotobservethistobeaseriousproblem.Figure2illustratestheinteractionbetweengenericsandownershipdomains:theStudentclassisparameter-izedbythestatedomainparameter.TheDataclassmaintainsaSequenceofStudentobjectsandisalsoparameterizedbystate.MethodDomainParameters.Java1.5annotationscannotbeaddedatmethodinvocationexpressions.Soweusedblockcom-mentstospecifytheactualdomainsforaparameterizedmethod(SeeFigure3foranexample).Unfortunately,evenproposalstoimprovetheJava1.5annotationfacilities[19]donotyetaddressaddingannotationstosuchexpressions.

DefaultingTool.Toreducetheannotationburden,weimple-mentedaseparatetooltoadddefaultannotationssuchasmarkingprivatefieldsasowned,methodparametersaslent,andStringsasshared.However,anannotationaddedbythedefaultingtool(e.g.,owned)mayneedtobemodifiedmanuallytosupplyactualdomainsfordomainparameters(e.g.,owned).

Annotation‘owner’.Wealsoaddedthespecialowneranno-tation,similartopeerinUniverses[17].Usingownercanofteneliminateadomainparameter:e.g.,inFigure1,Cons.ownerisSequence,SeqIterator.ownerisSequence.4.3

ToolLimitationsandFutureWork

Java1.5annotationssufferfromthefollowinglimitations:(1)Adeclarationcannothavemultipleannotationsofthesameannota-tiontype;(2)Annotationtypescannothavemembersofthetheir

4

classSequence{...

@DomainParams(\"TTowner\")/∗Methoddomainparameter∗/@Domain(\"shared\")/∗Domainforreturnvalue∗/staticString

toString(@Domain(\"lent\")Sequenceseq){...}

voiddump(){

@Domain(\"owned\")Sequenceseq=...;

@Domain(\"shared\")

/∗Provideusingblockcomment∗/Stringstr=Sequence.toString/∗∗/(seq);}}

Figure3.Declaringandbindingmethoddomainparameters.

while(objCourseFile.ready()){

this.vCourse.add(newCourse(courseFile.readLine()));}

/∗ABOVEMUSTBEREWRITTENAS....∗/while(objCourseFile.ready()){

@Domain(\"shared\")Stringline=courseFile.readLine();@Domain(\"state\")Coursecrs=newCourse(line);this.vCourse.add(crs);}

Figure4.Re-writinganewexpressionusinglocalvariables.

owntype;(3)Itisonlylegaltousesingle-memberannotationsforannotationtypeswithmultiplemembers,aslongasonememberisnamedvalue,andallothermembershavedefaultvalues.Oth-erwise,themoreverbosesyntaxisrequired,e.g.,@Name(first=\"Joe\last=\"Hacker\");(4)Annotationtypescannotextendanyentity(class,interfaceorannotation);and(5)Annotationsareallowedontype,field,variableandmethoddeclarationsandnotallowedontypeparametersormethodinvocations.

Thefistrestrictionpreventedusfromusingthe@Domainan-notationtospecifyboththeannotationonthereceiverandonthereturntypeofamethod.Thesecondrestrictionpreventedusfromhavingshorthandconstantannotationsforthespecialaliastypes,e.g.,@ownedinsteadof@Domain(\"owned\"):suchconstantscan-notbeusedinsideotherannotationsasin@Domain(annotation=@owned,parameters={@owned}).

Toavoidhavingmultiplewaysofindicatingthesamemean-ing,weusestringsforalltheannotationsandrequireannotationsoftheform@Domain(\"owned\").Althoughdevelopersmaybemorelikelytointroducespellingmistakesinstringannota-tions,thetypecheckerwillcatchtheseproblemsearlyenough.Thethirdrestriction,i.e.,thelackofpositionalarguments,requiredtheuseoftheverbosesyntax@Domains(publicDomains={\"d1\\"d2\"},privateDomains={\"pda\\"pdb\"}).

Thefinalrestrictionandthecurrentlackofannotationinferencerequireconvertingsomeexpressionstomoreverboseconstructsbydeclaringlocalvariablesandannotatingthem.Themostcommonsuchexpressionswerenewexpressions(SeeFigure4)andcastexpressions(SeeFigure5).

Weplantoaddresssomeofthefollowinglimitations:

•Infermethoddomains:justasactualtypeargumentsdonothavetobepassedtoagenericmethodinJava,itmaybepossibletoinfer,inmostcases,theactualsformethoddomainparametersbasedonthetypesoftheactualarguments;

•Allowsuppressingmessages:sincereflectivecodecannotbeannotatedsuccessfullyusingownershipdomains[6];

2007/7/3

ArrayListvCourse=student.getRegisteredCourses();for(inti=0;iif(((Course)vCourse.get(i)).conflicts(course)){...}}

/∗ABOVEMUSTBEREWRITTENAS...∗/@Domain(\"lent\")

ArrayListvCourse=student.getRegisteredCourses();for(inti=0;i\")

Coursecrs=(Course)vCourse.get(i);if(crs.conflicts(course)){

...}}

Figure5.Re-writingacastexpressionusinglocalvariables.

•Displayannotationsmoreelegantly:anEclipseplug-inby

EisenbergandKiczales[18]canbeautifyJava1.5annotationsforinteractiveeditingwhiletheanalysisusesthesameAST.

5.OwnershipDomainsCaseStudies

Theannotation-basedsystemismostlycomplete—thedomainlinkchecksarestillbeingimplementedasofthiswriting.WeusedthetoolstoaddandcheckownershipdomainannotationsontworealJavaprogramswitharound15,000linesofcodeeach.

JHotDraw.ThesubjectsystemforthefirstcasestudyisJHot-Draw[23].Version5.3hasaround200classesand15,000linesofJava.JHotDrawisrichwithdesignpatterns[22],usesbothcom-positionandinheritanceheavilyandhasevolvedthroughseveralversions.Wefirstusedthedefaultingtoolthenmanuallymodifiedtheannotationsasneeded.Addingannotationswasiterative.Forinstance,overseveraliterations,wemademoreuseoftheownedannotation.JHotDrawwasannotatedwithoutmakinganystructuralrefactoringsuchasextractinginterfaces,etc.Somecodechangeswereneededhowevertouseourannotationsystem,e.g.,extractalocalvariablefromanewexpressionandaddanannotationonthelocalvariable,convertananonymousclasstoanestedclasstoadddomainparameterstoit,etc.JHotDrawVersion5.3didnotusegenerictypes,soweusedEclipserefactorings[21]toinfergenerictypesofcontainers.

HillClimber.Bymanyaccounts,JHotDrawisconsideredthebrainchildofexpertsinobject-orienteddesignandprogramming.Incomparison,thesubjectsystemforthiscasestudy,HillClimber,isanother15,000lineapplicationthatwasmainlydevelopedandmaintainedbyundergraduates[2].Inpreviouswork,were-engineeredtheoriginalJavaprogramtoanArchJava[4]imple-mentationwithownershipdomainannotations,butusinglanguageextensionsinsteadofJava1.5annotations[2].There-engineeringcasestudyalsoproducedaversionthatrefactoredtheoriginalcodebymakingmostclassfieldsasprivate[2].Forthiscasestudy,westartedfromtherefactoredJavacodeandaddedownershipdomainannotationstoit.

UnlikeJHotDraw,addingannotationstoHillClimberinvolvedrefactoringtodecouplethecodeasdiscussedbelow.Wealsorefac-toredthecodetousegenerics,mostlyautomaticallyusingEclipse.However,EclipsecannotinferthegenerictypeofavariableoftypeVectorstoringarraysofNodeobjects.SuchcodewasmanuallyrefactoredtouseVector>.

Comparedtotheearliercasestudywithlanguageextensions[2],theannotation-basedsystemallowedusingEclipserefactoringtoolstoextractinterfacesandinfergenerictypeswhileaddingtheownershipdomainannotations.Comparingthenumberofhourswouldnotbemeaningfulsincetheannotation-basedsystemwasstillunderdevelopmentwhilethecasestudywasunderway,and

5

thatwouldnotaccountforthelearningeffectofannotatingthesameprogramtwice.Anecdotally,weweremoreproductivewiththeannotation-basedsystemthanwiththeearliertoolusinglan-guageextensions.Theoverallprocesschangedaround40%ofthelinesofcodeinHillClimber.The40%codechangesincludedboil-erplateimportstouseourJava1.5annotations,andcodechangestosupportaddingannotationstosomeexpressions.Tomoreaccu-ratelygaugethemanualannotationoverhead,anAST-visitorwasusedtocounttheinstanceswherethecurrentannotationisthesameastheonegeneratedbythedefaultingtool:over40%oftheannota-tionswereexactlythesameasthedefaultonesforHillClimber;thatnumberwasaround30%forJHotDraw.Thereare60typeerrorsre-maininginJHotDrawand42errorsremaininginHillClimber.Inthisfollowingdiscussion,weillustrateusingactualexamplesfromJHotDrawandHillClimber,howownershipdomainscanex-pressandenforcedesignintentrelatedtoobjectencapsulationandcommunication,usingcodesnippetsfromthesubjectsystems.Thecodewasslightlyeditedforpresentationbyremovingtrivialmodi-fiers.Somecodeishighlightedusingunderlining.

5.1Ownershipdomainsenforceinstanceencapsulation

Allownershiptypesystemscanexpressandenforceinstanceen-capsulationwhichisstrongerthanthemodulevisibilitymechanismofmakingafieldprivate.Inownershipdomains,placingafieldintheprivateowneddomainmeansthattheobjectcanbereachedonlybygoingthroughitsowner;asaresult,noaliasestothatobjectcanleaktotheoutside.ConsiderCompositeFigureinJHotDraw:

@Domains({\"owned\"})

@DomainParams({\"M\"})...

abstractclassCompositeFigure...{

//Thefiguresthatcomprisethisfigure

@Domain(\"owned>\")Vector

fFigures;/∗∗

∗Addsavectoroffigures.∗/

voidaddAll(@Domain(\"M>\")Vector

figs){//Cannotassignobjectin”M”to”owned”//this.fFigures=figs;//ThisiscorrecthoweverfFigures.addAll(figs);}...}

AnnotatingfieldfFigureswithownedencapsulatesthelistofcompositeFigures(fFigures)topreventobjectsthatonlyhaveaccesstothecompositeobjectfrommodifyingthelistdirectly.Ifadevelopertriestosubvertthelanguagevisibilitymechanismsbyexposingaprivateorprotectedfieldusingapublicaccessormethod,theownershipdomainstypesystemprohibitsapublicmethodfromhavinganownedparameterorreturnvalue.LettingEclipsegenerateasetterforthefFiguresfieldproducesthefol-lowingcode—withoutannotations:

voidsetFFigures(Vector

figs){this.fFigures=figs;}

Uponaddingtheannotations,adevelopercanrealizethatthesetterisoverwritingtheexistingfieldsincetheparameterfigscannotbemarkedasownedandanyotherannotationwouldfailtheassignmentcheckwhenoverwritingthefFiguresfield.

Whenmanuallyaddingannotations,itispossibletomissmanyopportunitiesformakingobjectsowned.Indeed,weinitiallyanno-tatedfFigureswiththedomainparameterMinsteadofowned.Insomecases,objectsshouldbeownedbutarenot,andmakingthemownedmayrequirecodechanges,e.g.,toreturnacopyofanobjectinsteadofanaliastoaprivatefield.

2007/7/3

Visualizingtheannotationsencouragedustomakemoreuseoftheownedannotationsinceownedavoidsclutteringthetop-leveldomains[1].Perhapsbettertoolsupportcanpromptadevelopertoencapsulateafieldthatcouldbeannotatedwithownedbutisnot,e.g.,alightweightcompile-timeownershipinferencealgorithm[33]couldsuggestpossibleEclipse“quickfixes”.5.2

Ownershipdomainsspecifyarchitecturaltiers

AtieredarchitectureisoftenusedtoorganizeanapplicationintoaUserInterfacetier,aBusinessLogictier,andaDatatier.Ownershipdomainscanexpressandenforcesuchatieredruntimearchitecturebyrepresentingatierasanownershipdomain[3],andapermissionbetweentiersasadomainlinktoallowobjectsintheUserInterfacetiertorefertoobjectsintheBusinessLogictierbutnotviceversa.SuchanarchitecturalstructureandconstraintscannotbeeasilyexpressedinplainJavacode.

WeorganizedthecoreJHotDrawtypesinFigure6accordingtotheModel-View-Controllerdesignpatternasfollows:

•Model:consistsofDrawing,Figure,Connector,etc.ADrawingiscomposedofFigureswhichknowtheircontainingDrawing.AFigurehasalistofHandlestoallowuserinterac-tions.ADrawingalsoextendsFigureChangeListener(notshown)tolistentochangestoitsFigures.

•View:consistsofDrawingEditor,DrawingViewandassoci-atedtypes.DrawingViewextendsDrawingChangeListener(notshown)tolistentochangestoDrawingobjects.

•Controller:includesinterfacessuchasHandle,ToolandCommand.AToolisusedbyaDrawingViewtomanipulateaDrawing.ACommandencapsulatesanactiontobeexecuted—asimpleinstanceoftheCommanddesignpattern[22,p.233]withoutundosupport.

Oncewedefinedthethreetop-levelownershipdomains,Model,ViewandController,wepassedthecorrespondingdomainpa-rametersM,VandCtovarioustypesasdiscussedbelow.Avisual-izationoftheJHotDrawexecutionstructurebasedontheseowner-shipdomainannotationsisavailable[1].

InHillClimber,theapplicationwindowusesacanvastodis-playnodesandedgesofagraphinordertodemonstratealgo-rithmsforconstraintsatisfactionproblemsprovidedbytheengine.SoweorganizedtheHillClimbertypesinFigure12asfollows.Thedataownershipdomainstoresthegraphobjects(instancesofGraph,Node,etc.,andthoseoftheirsubclasses,HillGraph,HillNode,etc.).Theuidomainholdsuserinterfaceobjects.ThelogicdomainholdsinstancesofHillEngine,Search(andsub-classesthereof)objects,andassociatedobjects.AvisualizationoftheHillClimberexecutionstructurebasedontheseownershipdo-mainannotationsisavailable[1].5.3

Ownershipdomainsexposeimplicitcommunication

Designpatterns—suchasObserver[22,p.293],usedtodecoupleobject-orientedcodealsotendtomakethecommunicationbetweenobjectsimplicit.Addingownershipdomainannotationshelpsmakethatcommunicationmoreexplicit.

WeinitiallywantedtoparameterizeDrawing(SeeFigure7)withonlytheMdomainparameter,butDrawingChangeListenerisimplementedbyDrawingView.SoDrawingChangeListenerneededtobeannotatedwiththeVdomainparametercorrespond-ingtotheView.Bymakingimplicitcommunicationexplicit,anno-tationsseemtoprematurelyconstrainDrawingChangeListenerobjectstobeintheViewdomain.SinceDrawingwasacoreinter-facereferencedbyotherinterfacesinthecoreframeworkpackage,thisledtopassingallthreedomainparameterstomanyadditionalinterfacesandclasses.

ItistruethatifDrawinghadtobeparameterizedbydomainparameterVforsomeotherreason,theimplicitcommunicationin

6

/∗∗

∗DrawingisacontainerforFigures.Drawingsends∗outDrawingChangedeventstoDrawingChangeListeners∗wheneverapartofitsareawasinvalidated.

∗TheObserverpatternisusedtodecoupletheDrawing∗fromitsviewsandtoenablemultipleviews.∗/

@DomainParams({\"M\",\"V\"})

@DomainInherits({\"FigureChangeListener\",...})

interfaceDrawingextendsFigureChangeListener...{//Addsalistenerforthisdrawing.voidaddDrawingChangeListener(

@Domain(\"V\")DrawingChangeListenerl);//Addsafigureandsetsitscontainer//torefertothisdrawing.@Domain(\"M\")

Figureadd(@Domain(\"M\")Figurefigure);...}

Figure7.AddingannotationstoDrawing.

@DomainParams({\"M\",\"V\",\"C\"})interfaceHandle{

voidinvokeStart(@Domain(\"V\")DrawingViewv);...

@Domain(\"M\")UndoablegetUndoActivity();}

Figure8.HandlewithM,VandCdomainparameters.theobserverwouldnothavebeendiscoveredthisway.Ownershipdomainannotationshelpmakeimplicitcommunicationexplicitwhenareferencerequirespermissiontoaccessanewpartoftheprogramforthefirsttime.

InHillClimber,addingownershipdomainannotationsexposedcovertobjectcommunicationthroughbaseclassesfromtwopar-allelinheritancehierarchies.Duringanearlyiteration,weparam-eterizedthebaseclassGraphCanvasbytheuianddatado-mainparameters.WethenrealizedthatGraph,thebaseclassforHillGraph,requiredtheuidomainparameter(SeeFigure12).ClassGraphonlyneededtheuidomainparametertoproperlyan-notateaGraphCanvasfieldreferencethatwedidnotexpect.ThisinturnrevealedthatHillGraphandHillCanvaswerecommu-nicatingthroughtheirbaseclassesGraphandGraphCanvas.Intheend,thereferencetoGraphCanvaswasmovedfromGraphtoHillGraphandgeneralizedasanIHillCanvasreferencebyex-tractinganinterfaceIHillGraphfromHillGraph.5.4Ownershipdomainsexposetightcoupling

Letustemporarilyignoretheearlierlimitationwithaddinganno-tationstothelistenersandassumethatDrawingcouldbeparam-eterizedbyonlytheMdomainparameter.LetusconsiderwhetheritwouldbepossibletoparameterizeinterfaceHandle(SeeFigure8)withdomainsMandC.AHandlewouldbeintheCdomainandwouldaccessobjectsinthatdomainandinMdomain,i.e.,itshouldnotaccessobjectsintheVdomainparameter.NotethateveniftheexplicitparameterCwasnotprovided,thatdomainwouldstillbeaccessibletoHandleusingtheownerannotation.

AcommentinthecodeindicatedthatVersion4.1deprecatedtheoriginalinvokeStartmethodwhichtookaDrawingobjectasoneofitsparameters,infavorofaninvokeStartmethodthattakesinsteadaformalparameterDrawingViewparameterizedbyM,V,andC.ThisrequiredpassingtoHandletheadditionaldomainparameterV.SinceHandleisacoreinterfacereferencedbyotherinterfacesinthecoreframeworkpackage,thisalsoledtopassingallthreedomainparameterstomanyadditionaltypes.

2007/7/3

Figure6.SimplifiedclassdiagramforJHotDraw(AdaptedfrommanualclassdiagrambyRiehle[43,12]).

@DomainParams({\"M\",\"C\"})interfaceHandle{@DomainParams({\"V\"})

voidinvokeStart(@Domain(\"V\")DrawingViewv);...

@Domain(\"M\")UndoablegetUndoActivity();}

Figure9.HandlewithonlyMandCdomainparameters.

@DomainParams({\"M\",\"C\"})

@DomainInherits({\"Handle\"})

abstractclassAbstractHandleimplementsHandle{//Willnottypechecksince’V’unbound@Domain(\"V\")DrawingViewview;...

@DomainParams({\"V\"})

voidinvokeStart(@Domain(\"V\")DrawingViewv){//Cannotstoreargumentinfield’this.view’}}

Figure10.Methoddomainparameterscanenforcelifetime.5.5

Ownershipdomainsexposeandenforceobjectlifetime

Letusassumeinthissectionthattherefactoringwhichintroducedthetightercouplingwasneverperformed,i.e.,HandlestillneededaDrawinginsteadofaDrawingView.UndosupportwasaddedtoJHotDrawforthefirsttimeinVersion5.3.Inparticular,HandlenowhadareferencetoUndoable—whichinturnrequireddomainparametersM,VandCbecauseUndoable’sgetDrawingView()methodreturnedaDrawingView.

Now,letusseeifitwouldbepossibletoannotateUndoableandHandlewithonlythedomainparametersMandC(SeeFigure9)—thedomainparameterVcanthenbesuppliedtoinvokeStart()asamethoddomainparameter.

Usingamethoddomainparametertoannotatetheformalpa-rametervcouldenforcetheconstraintthatadevelopershouldnotstoreinafieldtheDrawingViewobjectpassedasanargumenttoinvokeStart(),asinFigure10.Ofcourse,adevelopercouldstoretheDrawingViewobjectinafieldoftypeObject,butthatfieldwouldhavetobecasttoaDrawingViewtobeofanyuse.

7

Insteadofamethoddomainparameter,thelentannotationcouldalsobeusedtoallowatemporaryaliastoanobjectwithinamethodboundary.WefoundafewsuchexamplesinJHotDraw.MethodsetAffectedFiguresinFigure11makesacopyofthelentargumentsoitcannotjustholdontoit.

Infact,lentcanbeformallymodeledasamethoddomainpa-rameter.However,thetypesystemdoesnotallowamethodtore-turnalentvaluebutitallowsamethodtoreturnanobjectinamethoddomainparameter.InthecaseofDrawingView,lentcan-notbeusedbecauseimplementationsofinvokeStart()constructUndoableobjectsthatmaintainaliasestotheDrawingViewandthusrequiretheVdomainparameter.

Forthatsamereason,theUndoableinterfacerequirestheVdo-mainparameterbecauseUndoablestorestheDrawingViewwheretheactivitytobeundonewasperformedinordertoundothechangestothatviewonly.ThismayslightlyviolatetheModel-View-Controllerdesign,wheremodelobjectsshouldnotholdontoviewobjects,becausetheremightbemultipleviewsthatneedtobeupdatedinresponsetochangesinthemodel.Atthesametime,itwouldbecounter-intuitiveforausertoundoachangeinoneviewandobservechangesinsomeotherview.Thus,ownershipdomainannotationsexposethetightercouplingthattheUndofeaturein-troduced.Figure11showsinmoredetailtheinteractionbetweenHandle,UndoableandDrawingView.

AnearlierempiricalstudyofJHotDrawmentionedthat“acom-monarchitecturalmistake[...]wastoprovideFigureswitharef-erencetotheDrawingortheDrawingView.FiguresdonotbydefaulthaveanyaccesstoeithertheDrawingortheDrawingViewinwhichtheyarecontained.Thispreventsthemfromaccessingin-formationsuchasthesizeoftheDrawing.However,itispossibletoovercomethisproblembypassingtheviewintotheconstructorofafigure,whichcanthenstoreandaccessthisasrequired”[28].StartingwithVersion5.3,onecouldgettotheFigure’sHandlesthroughitshandles()methodthengetaDrawingViewthroughaHandle’sUndoActivityobjects.

5.6Ownershipdomainspromotedecouplingcode

Ownershipdomainannotationshighlighttightcouplingandpro-moteprogrammingpracticesthatdecouplecode.

ProgrammingtoanInterface.Itisrecommendedto“refertoobjectsbytheirinterfaces”[7,Item#34]sinceinterfacescanreduce

2007/7/3

@DomainParams({\"M\",\"V\",\"C\"})

@DomainInherits({\"LocatorHandle\"})classResizeHandleextendsLocatorHandle{@Override

voidinvokeStart(intx,inty,

@Domain(\"V\")DrawingViewview){

setUndoActivity(createUndoActivity(view));...}/∗∗

∗Factorymethodforundoactivity.∗Tobeoverridenbysubclasses.∗/

protected@Domain(\"M\")UndoablecreateUndoActivity(

@Domain(\"V\")DrawingViewview){

@Domain(\"unique\")ResizeHandle.UndoActivity

undoable=newResizeHandle.UndoActivity(view);returnundoable;}

@DomainParams({\"M\",\"V\",\"C\"})

@DomainInherits(\"UndoableAdapter\")

staticclassUndoActivityextendsUndoableAdapter{...}

}/∗∗

∗BasicimplementationforanUndoableactivity∗/

@DomainParams({\"M\",\"V\",\"C\"})

@DomainInherits(\"Undoable\")

publicclassUndoableAdapterimplementsUndoable{@Domain(\"V\")DrawingViewmyDrawingView;

@DomainParams({\"ui\",\"logic\",\"data\"})@DomainInherits({\"Node\"})classHillNodeextendsNode{

@Domain(\"data\")HillGraphgraph;...}

Whenaddingannotations,anunexpecteddomainparameterof-tenindicatesunnecessarycoupling,e.g.,whyshouldHillNodehaveaccesstotheuidomain?Thusalengthydomainparameterlistcanbeanobjectivemeasureofacodesmell[2].Furthermore,own-ershipdomainannotationscanhelpadeveloperlowerthecouplingbysuggestingwhichspecifictypedeclarationsneedtobegeneral-izedtoshortenthelistofdomainparametersontheenclosingtype.InHillClimber,onesolutionwastoextractanIHillGraphin-terfacefromclassHillGraphthatonlyrequiresthedatadomainparameterandmakeaHillNodeobjectreferencetheHillGraphobjectthroughtheIHillGraphinterface.Wedecidedagainstcar-ryingthisrefactoringfurtherandeliminatingtheuiandlogicdo-mainparametersonHillGraphitself.

SincetheHillGraph,HillNode,etc.,formaparallelinheri-tancehierarchytoGraph,Node,etc.,asimilarrefactoringwasper-formedonGraphbyextractingaIGraphinterface–eventhoughGraphandIGrapharebothparameterizedbydata.

@DomainParams({\"ui\",\"logic\",\"data\"})@DomainInherits({\"Graph\",

\"IHillGraph\"})

classHillGraphextendsGraph

implementsIHillGraph{

...}

@DomainParams({\"data\"})UndoableAdapter(@Domain(\"V\")DrawingViewdv){

@DomainInherits({\"IGraph\"})setDrawingView(dv);

interfaceIHillGraphextendsIGraph{}

...@Domain(\"V\")DrawingViewgetDrawingView(){

}returnmyDrawingView;

@DomainParams({\"data\"})}

@DomainInherits({\"Node\"})voidsetDrawingView(@Domain(\"V\")DrawingViewdv){

classHillNodeextendsNode{myDrawingView=dv;

@Domain(\"data\")IHillGraphgraph;}

..voidsetAffectedFigures(@Domain(\"lent\")FigureEnumerationfe).{

//theenumerationisnotreusablethereforeacopyismade}//tobeabletoundo−redothecommandseveraltimerememberFigures(fe);}

}

Figure11.ConcreteimplementationclassofHandle.couplingbetweenclassesbysplittingintentfromimplementation.Whenfewerdomainparametersareneededtoannotateaninter-face(ascomparedtothecorrespondingclass),ownershipdomainannotationscanenforcethisidiom.

Inparticular,animplementationclasscanrequireaprivateownershipdomaintobepassedasanactualvalueforoneitsparameters.Sinceaprivateownershipdomaincannotbenamedbyanoutsideclient,theclientisthenforcedtousetheinterfacewhichdoesnotrequiretheseparameters.

Forinstance,intheearlierSequenceexample(Figure1),theSeqIteratorclassreceivestheSequence’sprivatedomainownedandhidestheextraparameterizationbehindtheIteratorinterface.ThisforcesaclientoftheSequencetoaccesstheitera-torobjectsonlythroughtheIteratorinterface.AclientmaynotevencasttheIteratorreferencetoaSeqIteratorclass.

WeusedasimilartechniquetodecouplethecodeinHillClimber(SeeFigure12fortheinheritancehierarchy).Theoriginalim-plementationforclassHillNodehadafieldreferenceoftypeHillGraph.However,HillGraphtookthethreedomainparam-etersui,logicanddata,whichrequiredpassingallthoseparam-eterstoHillNode.

8

TightlycoupledcodewasobservedthroughoutHillClimber.Similarly,weweresurprisedthatadialogclassFontDialogre-quiredthedatadomainparameter.ItturnedoutthatFontDialoghadafieldreferencedeclaredwithitsmostspecifictypeGraphCanvas.Insomecases,itispossibletogeneralizethetypeofthereference,e.g.,usejava.awt.Frametoeliminatetheneedforthedomainparameter.However,FontDialogneededaccesstosomeoftheGraphCanvasfunctionality,soadifferentsolutionwasneeded.MediatorPattern.Defininganinterfaceissometimesinsuffi-cienttodecouplecodesincereferringtoanobjectthroughitsinter-facestillrequiresaccesstothedomaintheobjectisin.OnesolutionistousetheMediatordesignpattern[22,p.273],asshownhere.IntheoriginalHillClimberimplementation,NodeobtainedareferencetoGraphCanvas,whichviolatestheLawofDemeter[32],i.e.,objectsshouldonlytalktotheirimmediateneighbors:

@DomainParams({\"data\"})abstractclassEntity{

@Domain(\"data\")Graphgraph;//parentgraph...}

@DomainParams({\"data\"})

@DomainInherits({\"Entity\"})classNodeextendsEntity{...

intgetHeight(){

returngraph.getCanvas().getFontMetrics()...;}}

2007/7/3

graphFramework::EdgegraphFramework::NodegraphFramework::GraphgraphFramework::GraphCanvasHillGraph0..1 - hillGraph - hillCanvasHillEdge0..1HillNode # node - currNode0..1Search0..1 # engine0..1Hill - hillEngine0..1 - hillWindowHillCanvas0..1HillEngineHillWindowGreRRSearchRandSearchSimpleSearchSimAnnealSearchSimRanSearchGreedySearchMCHSearchRdWkSearchFigure12.PartialUMLClassDiagramforHillClimberobtainedfromtheoriginalimplementationusingEclipseUML[39].Thisdiagramdoesnotreflectsomeofthetypesintroducedduringrefactoring,suchasIGraph,IHillGraphandICanvasMediator.ExtractinganinterfacefromGraphCanvaswouldnotwork,asthatreferencewouldstillneedtheuidomainparameter.Moreover,theimplementationofgetFontMetrics()couldnotbemovedtoGraphasitrequiredaccesstoobjectsintheuidomain.@DomainParams({\"data\"})abstractclassEntity{@Domain(\"ui\")IGraphCanvascanvas;//‘ui’unbound...}/∗∗∗DrawApplicationdefinesastandardpresentation∗forstandalonedrawingeditors∗/@DomainParams({\"M\",\"V\",\"C\"})@DomainInherits({\"DrawingEditor\",...)classDrawApplicationimplementsDrawingEditor...{//Opensanewwindowwithadrawingview.@DomainReceiver(\"unique\")protectedvoidopen(...){fIconkit=newIconkit(this);...}}classIconkit{static@Domain(\"unique\")IconkitfgIconkit=null;//ConstructsanIconkitthatusesthegiveneditor//toresolveimagepathnames.@DomainReceiver(\"unique\")

publicIconkit(@Domain(\"unique\")Componentcomp){fgIconkit=this;...}}

Amediatorwasdefinedasfollows:/∗∗∗Mediatorinterface∗/interfaceICanvasMediator{@Domain(\"shared\")FontMetricsgetFontMetrics();...}/∗∗

∗Mediatorimplementationclass∗/

@DomainParams({\"ui\",\"data\"})

classMediatorImplimplementsICanvasMediator{@Domain(\"ui\")GraphCanvascanvas;

MediatorImpl(@Domain(\"ui\")GraphCanvasc){this.canvas=c;}

@Domain(\"shared\")FontMetricsgetFontMetrics(){returncanvas.getFontMetrics();}...}

Figure13.Annotatingasingletonusingunique.

GraphCanvasinitializesthemediator:

@DomainParams({\"ui\",\"data\"})classGraphCanvasextends...{

@Domain(\"data\")MediatorImplmediator;...

@Domain(\"data\")ICanvasMediatorgetMediator(){

returnmediator;}}

@DomainParams({\"data\"})

@DomainInherits({\"Entity\"})classNodeextendsEntity{intgetHeight(){

returngetMediator().getFontMetrics()...;}

5.7OwnershipdomainscanhelpidentifysingletonsWhileaddingownershipdomainannotations,wediscoveredacu-riousinstanceoftheSingletondesignpattern:IconKit’sconstruc-torwasnotprivate,althoughithadastaticinstance()method.Indeed,thereisauniqueinstanceofDrawingEditor(theappli-cationitself)andauniqueIconKit(SeeFigure13)atruntime.

EntityandNodecanthenusethemediatorasfollows:

@DomainParams({\"data\"})abstractclassEntity{

@Domain(\"data\")ICanvasMediatormediator;...}

6.ExpressivenessChallenges

Inthissection,wediscusssomeoftheexpressivenessgapsthatweencountered,someofwhichhadbeenpreviouslymentioned.

9

2007/7/3

classDrawApplicationimplementsDrawingEditor...{...

classMDIDrawApplicationextendsDrawApplication...{...

@DomainParams({\"M\",\"V\",\"C\"})

@DomainInherits({\"MDI_DrawApplication\"})classJavaDrawAppextendsMDIDrawApplication{...

@Domains({\"Model\",\"View\",\"Controller\"})classMain{

@Domain(\"View\")JavaDrawAppapp=newJavaDrawApp();publicstaticvoidmain(

@Domain(\"lent[shared]\")Stringargs[]){@Domain(\"lent\")Mainsystem=newMain();}}

Figure14.Definingthetop-leveldomainsinaseparateclass.6.1

Anobjectcannotbeinmorethanoneownershipdomain

Ownershipdomains,asmostotherownershiptypesystems,supportonlysingleownership,i.e.,anobjectcannotbepartofmorethanoneownershiphierarchy.Proposalsformultipleownership[11]liftthisrestrictioninothertypesystems.Ownershipdomainsdonotsupportownershiptransfer[31]either,i.e.,anobject’sownerdoesnotchange—onlyuniqueobjectscanflowbetweenanytwodomains.Asaresult,manyfine-grainedownershipdomainscannotbedefinedtorepresentmultiplerolesindesignpatterns:e.g.,ifanobjectisbothamediatorintheMediatorpatternandaviewintheModel-View-Controllerpattern,itcannotbeinbothaMediatorownershipdomainandaViewownershipdomainatthesametime.Forinstance,creatingtop-levelownershipdomainstocorre-spondtothedesigninFigure6wouldhavebeenmorechalleng-ingthancreatingthethreetop-leveldomainsforModel,ViewandController:placingaDrawingEditorobjectinaMediatordo-mainwouldhaveprohibiteditfromalsobeingintheViewdomain.6.2

AnobjectcannotplaceitselfinadomainitdeclaresAnobjectcannotplaceitselfinanownershipdomainthatitde-clares.Thisisproblematicfortherootapplicationobject,i.e.,theJavaDrawAppinstance(JavaDrawAppextendsDrawApplicationwhichinturnextendsDrawingEditor).Truetoform,wesolvethisproblemwithanextralevelofindirectionbycreatingafaketop-levelclassMaintodeclaretheModel,ViewandControllertop-levelownershipdomainsanddeclaretheJavaDrawAppobjectintheViewdomain(SeeFigure14).6.3

Publicdomainsarehardtouse

Publicdomainsmaketheownershipdomainstypesystemmoreflexiblethanowner-as-dominatortypesystems[15].Also,publicdomainsareidealforvisualizationbecauseplacinganobjectinsideapublicdomainofanotherobjectrelatestheseobjectswithoutclutteringthetop-leveldomains[1].However,publicdomainsaretypicallyhardtousewithoutrefactoringthecode.Westartedusingtheminafewcasesbutquicklyabandonedthoseattempts.

SincetheObserverdesignpatterntendstomakecommunica-tionbetweenobjectsimplicit,weattemptedtorepresentlistenersmoreexplicitlyusingownershipdomainannotations.Forinstance,itmightmakesensetocreateapublicdomainLISTENERSasado-maintoholdtheListenerobjectsthatanObserverwillnotify—aListeneroftenneedsspecialaccesstotheObserver,butusuallydoesnotneedspecialaccesstotheSubject.

JHotDrawusesadelegation-basedeventmodel:forinstance,aDrawingViewcallsmethodfigureSelectionChangedtono-tifyaFigureSelectionListenerobserverofselectionchanges.SoitmightmakesensetodeclareaFIGURESELECTIONLISTENERS

10

/∗∗

∗DrawingViewrendersaDrawingandlistenstoits∗changes.Itreceivesuserinputanddelegates∗ittothecurrentTool.∗/

@DomainParams({\"M\",\"V\",\"C\"})

@DomainInherits({\"DrawingChangeListener\"})

interfaceDrawingViewextendsDrawingChangeListener...{//AddalistenerforselectionchangesvoidaddFigureSelectionListener(

@Domain(\"?\")FigureSelectionListenerfsl);...}

@Domains({\"owned\"})

@DomainParams({\"M\",\"V\",\"C\"})

@DomainInherits({\"DrawingView\"})

classStandardDrawingViewimplementsDrawingView...{//Registeredlistoflistenersforselectionchangesprivate@Domain(\"owned>\")

VectorfSelectionListeners;StandardDrawingView(

@Domain(\"V\")DrawingEditoreditor,...){//editorisin’V’domainparameter,not’C’!addFigureSelectionListener(editor);...}

//Addalistenerforselectionchanges.

//CommandimplementsFigureSelectionListener//butCommandisinthe’C’domainparameter!voidaddFigureSelectionListener(

@Domain(\"?\")FigureSelectionListenerfsl){fSelectionListeners.add(fsl);}

Figure15.HowtoannotateaddFigureSelectionListener?publicdomainonCommandtoholdtheFigureSelectionListenerobjects.ButCommandimplementsFigureSelectionListener,soaCommandis-aFigureSelectionListener.ThusaCommandobjectcannotsplitapartofitselfandplaceitinthepublicdomainFIGURESELECTIONLISTENERSthatitdeclares.6.4Listenerobjectsareparticularlychallenging

TherewereadditionalcomplicationswhentryingtohighlighttheeventsubsysteminJHotDrawusingownershipdomainannota-tions.Command,whichisintheControllerdomain,implementsFigureSelectionListener,andsodoesDrawingEditor,whichisintheViewdomain.

ConsidermethodaddFigureSelectionListenerin(See

Figure15).HowwouldoneannotatetheformalparameterFigureSelectionListTheparametershouldsupportbothannotationsCandV.Existentialownership[13,29,34]maybetheanswertoincreasetheexpressiveness,e.g.,byannotatingtheparameterwith“any”[34].Otherproblemsofaddingownershipdomainsannotationstolistenershadbeenpreviouslyidentified[44].6.5Staticcodecanbechallenging

Eveninsuchawell-designedprogramasJHotDraw,wefoundafewinstanceswhereownershipannotationscannotbemadetotype-check.Inparticular,inFigure16,thestaticHashtablecannothavetheM,V,andCdomainparametersbecausethedomainparametersdeclaredontheclassNullDrawingViewarenotinscopeforstaticmembers.Staticmemberscanonlybeannotatedwithsharedorunique,andthesevaluescannotflowtotheMx,VxorCxmethoddomainparameters.

AnnotatingthegenericHashtablealsorequiresnestedparam-eters:Hashtablehasthreedomainparametersforitskeys,valuesandentries.BothDrawingViewandDrawingEditortakeM,V,andCasparameters.Althoughthenumberofannotationsseemsexcessiveandmaybearguesinfavorofgenericownership[41],the

2007/7/3

@DomainParams({\"M\",\"V\",\"C\"})

@DomainInherits({\"DrawingView\"})

classNullDrawingViewimplementsDrawingView...{static@Domain(\"unique,?,?>\")

HashtabledvMgr=...;@DomainParams({\"Mx\",\"Vx\",\"Cx\"})

publicsynchronizedstatic@Domain(\"Vx\")DrawingViewgetManagedDrawingView(

@Domain(\"Vx\")DrawingEditored){if(dvMgr.containsKey(ed)){@Domain(\"Vx\")

DrawingViewdv=dvMgr.get(ed);returndv;}...}

Figure16.Howtoannotateobjectsythatarestoredinstaticfields?ownershipdomainsfortheHashtablekey,valueandentriesneednotcorrespondtotheM,VandCownershipdomains.

Asolutionthatisnottype-safewouldbetostoretheHashtableasObject,thencastdowntoaHashtableuponuse—theequiv-alentofrawtypesbutwithoutre-implementingthemintheown-ershipdomainstypesystem.Anothersolutionwouldbetorefactortheprogramtoeliminatethisstaticfieldsinceitgivesanyobjectac-cesstoalltheDrawingViewandDrawingEditorobjects.Sinceitisoftenunrealistictoperformsuchasignificantrefactoring,maybethebestsolutionwouldbetosupportpackage-levelstaticowner-shipdomains,similartoconfinedtypes[9].6.6

Annotationsmaybeunnecessarilyverbose

Ownershipdomainannotationstendtobeverbose:e.g.,formalmethodparametersneedtobefullyannotatedeveniftheyarenotusedinthemethodbodyorusedinarestrictedway.Thisproducesparticularlyunwieldyannotationsforcontainersofgenerictypes.InFigure17,methodclearStackVerboseindicatesthecur-rentlevelofannotationsneeded.Itshouldbepossibletoleaveoutdomainparameterswhentheyarenotreallyneeded.ThismayinvolveusingimplicitexistentialownershiptypesasinclearStackAny:i.e.,thereexistssomedomainparametersd1,d2,d3,d4,suchthattheformalmethodparameterscouldbean-notatedwithlent>.Usingappropriatedefaults,theannotationscouldprobablybereducedtothelevelneededtoannotatearawtype,asshowninclearStack.6.7

ManifestownershipcanreducetheannotationburdenThecurrentdefaultingtoolonlyaddsthesharedannotationtoStringobjects.However,duringtheannotationprocess,wefoundourselvesaddingthesharedannotationtomanyothertypessuchasFont,FontMetrics,Color,etc.Specifyingaper-typedefaultgloballyandnotforeveryinstance,asinmanifestownership[13],wouldhavereducedtheannotationburden.6.8

Reflectivecodecannotbeannotated

JHotDrawusesreflectivecodetoserializeanddeserializeitsstateandsuchcodecannotbeannotatedusingownershipdomains[6].6.9

AnnotateExceptionsaslent

Weannotatedexceptionswithlentsincewewerenotparticularlyinterestedinreasoningaboutthem.However,richerannotationsarepossible[45].

7.RelatedWork

Casestudiesapplyingownershiptypesystemsonrealcodearefewandfarbetween.H¨achler[25]documentedacasestudyapplying

11

@Domains({\"owned\"})

@DomainParams({\"M\",\"V\",\"C\"})publicclassUndoManager{/∗∗

∗Collectionofundoactivities∗/

@Domain(\"owned>\")VectorundoStack;voidclearStackVerbose(

@Domain(\"lent>\")Vectors){s.removeAllElements();}

voidclearStackAny(

@Domain(\"lent>\")Vectors){s.removeAllElements();}

voidclearStack(

@Domain(\"lent\")Vectors){s.removeAllElements();}}

Figure17.Reducingannotationswhentheyarenotreallyneeded.Universes[36,17]onanindustrialsoftwareapplicationandrefac-toringthecodeintheprocess.AlthoughthesubjectsysteminthecasestudyislargerthanJHotDraw(around55,000linesofcode),theauthorannotatedonlyaportionofthesystem.Theauthorman-uallygeneratedvisualizationsoftheownershipstructurewhereaswehadaccesstotoolsupporttovisualizetheownershipstructureandadjusttheannotationsaccordingly[1].N¨ageli[38]evaluatedhowtheUniversesandOwnershipDo-mainstypesystemsexpressthestandardobject-orienteddesignpat-terns[22].However,inrealworldcomplexobject-orientedcode,designpatternsrarelyoccurinisolation[43].Aswediscussedear-lier,thesesubtleinteractions,combinedwiththesingleownershipconstraintofthetypesystem,maketheannotationsdifficult.

Inapreviouscasestudy,were-engineeredHillClimberusingArchJava[4]tospecifyacomponent-and-connectorarchitectureincodeandownershipdomainannotationstospecifythedatasharing[2].Intheearliercasestudy,weperformedrefactoringssimilartotheonesdescribedhere.However,addingownershipdomainanno-tationstotheArchJavaprogramseemedeasier.Indeed,ArchJava’sportconstructeffectivelyreducescoupling;intheplainJavaim-plementation,thesameeffecthadtobeachievedusingprogram-mingtointerfaces,usingmediators,etc.

ArchJava’spropertiesareavailableattheexpenseofvariousre-strictionsonobject-orientedimplementations.Thepreviouscasestudyalsoidentifiedthataddingownershipdomainannotationsre-quiredlesseffortthanencodingthearchitecturalstructureinArch-Java[2,6].Fewerdefectsareintroducedsincecodethatpassesob-jectreferencesneednotbechangedandtheownershipannotationsneednotaffecttheruntimesemanticsoftheprogram.Moreover,theownershipdomainannotations,whiletedioustoaddmanually,arerelativelystraightforwardoncethetop-leveldomainsaredecided,comparedtore-engineeringtouseArchJava.

Addingownershipdomainsannotationsmanuallystillrequiredsignificanteffort,andresearchersarestilllookingatscalableinfer-enceofownershipdomainannotations[6,16].Currentinferencetechniques[35,33]howeveronlyinfertheequivalentofowned,shared,lentanduniqueannotations,i.e.,theyassumeastrictowner-as-dominatorhierarchywhichisnotflexibleenoughtorep-resentmanydesignpatterns.Someapproachesdonotmapthere-sultsoftheanalysisbacktoanownershiptypesystem[35,33].Afullyautomatedinferencecannotcreatemultiplepublicdomainsinoneobjectandmeaningfuldomainparameters,whicharecriticalforrepresentingtheabstractdesignintent,asinthethreetop-level

2007/7/3

Model,View,andControllerdomainsinJHotDraw.Existingin-ferencealgorithmsoftengenerateimpreciseannotations,producingforeachclassalonglistofdomainparameters,oftenplacingeachfieldinaseparatedomain,andannotatingmanymoreobjectsassharedorlentthannecessary[6,16].

8.Conclusion

Wepresentedanannotation-basedsystemthatre-implementstheownershipdomainstypesystemasasetofJava1.5annotations,usingtheEclipseinfrastructure.Usingannotationsimposesmanyrestrictionsandrequireschangingthecodeslightlytoaddanno-tationstoit,andtheannotationlanguagedoestakesomegettingusedto.Still,theannotation-basedsystemisanimprovementovercustominfrastructure,languageextensions,andtheresultinglim-itedtoolsupport:itenabledustoannotatelargerobject-orientedprograms“inthewild”tostudyhowownershipdomainscanex-pressandenforcedesignintentrelatedtoobjectencapsulationandcommunicationandtoidentifyexpressivenesslimitations.

Infuturework,weplanonmakingthetypesystemmoreflexibleandextendingtheannotationlanguageinanon-breakingway.

Acknowledgments

ThisworkwassupportedinpartbyNSFgrantCCF-0546550,DARPAcontractHR00110710019,theDepartmentofDefense,andtheSoftwareIndustryCenteratCarnegieMellonUniversityanditssponsors,especiallytheAlfredP.SloanFoundation.

References

[1]M.Abi-AntounandJ.Aldrich.Compile-TimeViewsofExecution

StructureBasedonOwnership.InIntl.WorkshoponAliasing,ConfinementandOwnership,2007.[2]M.Abi-Antoun,J.Aldrich,andW.Coelho.ACaseStudyinRe-engineeringtoEnforceArchitecturalControlFlowandDataSharing.J.SystemsandSoftware,80(2),2007.[3]J.AldrichandC.Chambers.OwnershipDomains:Separating

AliasingPolicyfromMechanism.InECOOP,2004.[4]J.Aldrich,C.Chambers,andD.Notkin.ArchJava:Connecting

SoftwareArchitecturetoImplementation.InICSE,2002.[5]J.AldrichandD.Dickey.TheCrystalDataFlowAnalysisFramework

2.0.http://www.cs.cmu.edu/~aldrich/courses/654/,2006.[6]J.Aldrich,V.Kostadinov,andC.Chambers.AliasAnnotationsfor

ProgramUnderstanding.InOOPSLA,2002.[7]J.Bloch.EffectiveJava.Addison-Wesley,2001.

[8]B.BokowskiandA.Spiegel.Barat—AFront–EndforJava.

TechnicalReportB-98-09,FreieUniversit¨atBerlin,1998.[9]B.BokowskiandJ.Vitek.ConfinedTypes.InOOPSLA,1999.[10]C.Boyapati,B.Liskov,andL.Shrira.OwnershipTypesforObjectEncapsulation.InPOPL,2003.[11]N.Cameron,S.Drossopoulou,J.Noble,andM.Smith.Multiple

Ownership.InOOPSLA,2007.Toappear.[12]H.B.Christensen.Frameworks:PuttingDesignPatternsinto

Perspective.InSIGCSEInnov.&Tech.inComp.Sci.Ed.,2004.[13]D.Clarke.ObjectOwnership&Containment.PhDthesis,University

ofNewSouthWales,2001.[14]D.ClarkeandT.Wrigstad.ExternalUniquenessisUniqueEnough.

InECOOP,2003.[15]D.G.Clarke,J.M.Potter,andJ.Noble.OwnershipTypesforFlexible

AliasProtection.InOOPSLA,1998.[16]W.Cooper.InteractiveOwnershipTypeInference.SeniorThesis,

CarnegieMellonUniversity,2005.[17]W.DietlandP.M¨uller.Universes:LightweightOwnershipforJML.

JournalofObjectTechnology,4(8),2005.

12[18]A.D.EisenbergandG.Kiczales.ExpressiveProgramsthrough

PresentationExtension.InAOSD,2007.[19]M.D.ErnstandD.Coward.JSR308:AnnotationsonJavatypes.

http://pag.csail.mit.edu/jsr308/,2006.[20]UniversesTools.www.sct.ethz.ch/research/universes/tools/,

2007.[21]R.M.Fuhrer,F.Tip,A.Kiezun,J.Dolby,andM.Keller.Efficiently

RefactoringJavaApplicationstoUseGenericLibraries.InECOOP,2005.[22]E.Gamma,R.Helm,R.Johnson,andJ.Vlissides.DesignPatterns:

ElementsofReusableObject-OrientedSoftware.Addison-Wesley,1994.[23]Gamma,E.etal.JHotDraw.http://www.jhotdraw.org/,1996.[24]G.Goth.BewarethemarchofthisIDE:Eclipseisovershadowing

othertooltechniques.IEEESoftware,22(4),2005.[25]T.H¨achler.ApplyingtheUniverseTypeSystemtoanIndustrial

Application:CaseStudy.Master’sthesis,ETHZurich,2005.[26]JavaCC.https://javacc.dev.java.net/,2006.

[27]JSR175:AMetadataFacilityfortheJavaProgrammingLanguage.

http://jcp.org/en/jsr/detail?id=175,2006.[28]D.Kirk,M.Roper,andM.Wood.IdentifyingandAddressing

ProblemsinObject-OrientedFrameworkReuse.EmpiricalSoftwareEngineering,2006.[29]N.KrishnaswamiandJ.Aldrich.Permission-BasedOwnership:

EncapsulatingStateinHigher-OrderTypedLanguages.InPLDI,2005.[30]G.T.Leavens,K.R.M.Leino,andP.M¨uller.Specificationand

VerificationChallengesforSequentialObject-OrientedPrograms.FormalAspectsofComputing,2007.Submitted.[31]K.R.M.LeinoandP.M¨uller.ObjectInvariantsinDynamicContexts.

InECOOP,2004.[32]K.J.LieberherrandI.M.Holland.AssuringGoodStyleforObject-OrientedPrograms.IEEESoftware,6(5),19.[33]Y.LiuandA.Milanova.OwnershipandImmutabilityInferencefor

UML-basedObjectAccessControl.InICSE,2007.[34]Y.LuandJ.Potter.ProtectingRepresentationwithEffectEncapsula-tion.InPOPL,2006.[35]K.-K.MaandJ.S.Foster.InferringAliasingandEncapsulation

PropertiesforJava.InOOPSLA,2007.Toappear.[36]P.M¨ullerandA.Poetzsch-Heffter.Universes:ATypeSystemfor

ControllingRepresentationExposure.InA.Poetzsch-HeffterandJ.Meyer,editors,ProgrammingLanguagesandFundamentalsofProgramming,1999.[37]G.C.Murphy,M.Kersten,andL.Findlater.HowareJavaSoftware

DevelopersUsingtheEclipseIDE?IEEESoftware,23(4),2006.[38]S.N¨ageli.OwnershipinDesignPatterns.Master’sthesis,Department

ofComputerScience,FederalInstituteofTechnologyZurich,2006.[39]Omondo.EclipseUML.http://www.omondo.com/,2006.

[40]A.Potanin.OwnershipGenericJava.www.mcs.vuw.ac.nz/~alex/ogj/,

2005.[41]A.Potanin,J.Noble,D.Clarke,andR.Biddle.GenericOwnership

forGenericJava.InOOPSLA,2006.

[42]AnnotationFileUtilities.http://pag.csail.mit.edu/jsr308/annotation-file

2006.[43]D.Riehle.FrameworkDesign:aRoleModelingApproach.PhD

thesis,FederalInstituteofTechnologyZurich,2000.[44]J.Sch¨aferandA.Poetzsch-Heffter.SimpleLooseOwnership

Domains.InFTfJP,2006.[45]D.Werner,,andP.M¨uller.ExceptionsinOwnershipTypeSystems.

InFTfJP,2004.[46]ArchJava.http://www.archjava.org/,2007.

2007/7/3

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- vipyiyao.com 版权所有 湘ICP备2023022495号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务