aspects in aspectj - télécom sudparisgibson/teaching/csc7336/l2-aspectj.pdf · november 2017...
Post on 25-May-2020
16 Views
Preview:
TRANSCRIPT
CSC7336:AspectJ(JPGibson)November2017 1
AspectsinAspectJ
•Motivation•AspectOrientedProgramming:abriefintroductiontoterminology•Installation•Experimentation•AspectJ–somedetails•AspectJ–thingsyoushouldknowaboutbutwedonthavetimetocoverindetail•AspectJ–profilingproblem
CSC7336:AspectJ(JPGibson)November2017 2
Motivation
“Abilityiswhatyou'recapableofdoing.Motivationdetermineswhatyoudo.Attitudedetermineshowwellyoudoit.”LouHoltz
CSC7336:AspectJ(JPGibson)November2017 3
Motivation
Evenwelldesignedsystemshaveaspectsthatcutacrossalargenumberofthecomponents
Forexample,considerApacheTomcat,wherecertainaspectsoffunctionalityare:
•XMLparsing•URLpatternmatching•Logging•SessionManagement
Question:whichofthesearewelllocalised?
CSC7336:AspectJ(JPGibson)November2017 4
Motivation
XMLparsing
URLpatternmatching
Logging
SessionManagement:differenttypes
•ApplicationSession•ServerSession•StandardSession•Managers
Sothecodeforeachsessionstageshouldbewelllocalised?
CSC7336:AspectJ(JPGibson)November2017 5
Motivation
SessionExpiration:codeisdistributedthroughlotsofdifferentclasses
CSC7336:AspectJ(JPGibson)November2017 6
Motivation
SessionExpiration:abetterdesign?
Unfortunately,ifwedothiswewillhavetocompromisebyredistributingpreviouslylocalisedcode.
CSC7336:AspectJ(JPGibson)November2017 7
Motivation
SeparationofConcernsisatime-honouredprincipleofSoftwaredesign
D.Parnas.OntheCriteriatoBeUsedinDecomposingSystemsintoModules.Comm.ACM15,12(December1972),1053-1058.
Designprinciplesfordecomposition:•Information-hidingmodules•Identifydesigndecisionsthatarelikelytochange.•Isolatetheseinseparatemodules(separationofconcerns)
CSC7336:AspectJ(JPGibson)November2017 8
Motivation
Cross-Cutting Concerns
Inthemotivation,
•XMLparsingandURLpatternmatchingfittheclasshierarchy,•LoggingandSessionManagementdonot.
Across-cuttingconcernisonethatneedstobeaddressedinmorethanoneofthemodulesinthehierarchicalstructureofthesoftware.
Cross-cuttingconcernsarealsocalledaspects.
Whatisanaspectdependsonthechosendecomposition!
CSC7336:AspectJ(JPGibson)November2017 9
Motivation
ProblemswithCross-CuttingConcerns
Cross-cuttingconcernsposeproblemsforstandard,e.g.OO,programmingtechniques:
•hardanderror-pronetointroduceinanexistingsystem•hardtochangeafterwards•hardtounderstand/explaintonewcomers
Cross-cuttingimplementationofcross-cuttingconcernsdoesnotprovideseparationofconcerns.
CSC7336:AspectJ(JPGibson)November2017 10
Motivation
Solutions
Possibletreatmentofcross-cuttingconcerns:
Refactorthemaway.Changethemodulehierarchysothattheaspectbecomesmodular,oftenthroughapplicationofadequatedesignpatterns.
But:•oftenperformancepenaltiesthroughindirection•oftenleavessomecross-cuttingboiler-plate•can'thopetocaptureallaspects
CSC7336:AspectJ(JPGibson)November2017 11
AspectOrientedProgramming:abriefintroduction
AprogrammingmethodologyiscalledAspect-Orientedifitprovidespossibilitiestocleanlyseparateconcernsthatwouldotherwisebecross-cutting.
TherearevariousAspect-Orientedmethods.Theydifferinthekindsofaspectstheycanaddressandinthewaysaspectsandtheirrelationtothechosenhierarchicaldecompositionareexpressed.
CSC7336:AspectJ(JPGibson)November2017 12
AspectOrientedProgramming:abriefintroduction
Don’tForgetThatGoodDesignHelpsAvoidCrossCutting:soonlyuseAspectsiftheyarereallyneeded,andnotjustbecausethedesignisbad!
ExampleofGoodDesign–TheLawofDemeter:
Anobjectshouldonlycallmethodsonthis,instancevariables,methodarguments.
nothis.getWife().getMother().getMaidenName()chains.
Preventsdependencyontoomanyotherclasses.
The"LawofDemeter"providesaclassicsolution,see:
Lieberherr,Karl.J.andHolland,I. Assuringgoodstyleforobject-orientedprograms IEEESoftware,September1989,pp38-48
CSC7336:AspectJ(JPGibson)November2017 13
AspectOrientedProgramming:abriefintroduction
JoinPoints
Analysecommonlyoccurringaspects.Cross-cuttingimplementationscanoftenbeformulatedintermslike:
•Before...iscalled,alwayscheckfor...•Ifanyof...throwsanexception,...•Everytime...getschanged,notify...
ImplementationsofaspectsareattachedtocertainpointsintheImplementation,eg:
•methodcalls•constructorcalls•fieldaccess(read/write)•Exceptions
Thesecorrespondtopointinthedynamicexecutionoftheprogram.Suchpointsarecalledjoinpoints
CSC7336:AspectJ(JPGibson)November2017 14
AspectOrientedProgramming:abriefintroduction
CodeExample:FigureEditor(fromhttp://eclipse.org/aspectj/doc/released/progguide/)
CSC7336:AspectJ(JPGibson)November2017 15
AspectOrientedProgramming:abriefintroductionCodeExample:FigureEditor
A join point is a point in the control flow of a program
CSC7336:AspectJ(JPGibson)November2017 16
AspectOrientedProgramming:abriefintroduction
CodeExample:FigureEditor–joinpointsformoveBy
In aspect-oriented programming a set of join points is called a pointcut
Forexample,allcallsandreturnsfrommoveBymethods
CSC7336:AspectJ(JPGibson)November2017 17
AspectOrientedProgramming:abriefintroduction
Apointcutdesignatesasetofjoinpointsforanyprogramexecution.
Atexecution,anyjoinpointmayormaynotbeselectedbyapointcut.
Examples:•allcallstopublicmethodsofthePointclass•everyexecutionofaconstructorwithoneintargument•everywriteaccesstoapublicfield
Membershipofajoinpointmaybedeterminedatruntime
CSC7336:AspectJ(JPGibson)November2017 18
AspectOrientedProgramming:abriefintroduction
Advice
Adviceiscodethatshouldbeinsertedbefore,afteroreveninsteadofexistingcodeatsomesetofjoinpoints.
`Mainstream'AOP:
•Designatesetsofjoinpointsusingsomespecificationlanguageforpointcuts.•Declareadvicetobeexecutedbefore/after/insteadofthecalls/methodexecutions/fieldaccessesetc.selectedbythepointcut.
CSC7336:AspectJ(JPGibson)November2017 19
AspectOrientedProgramming:abriefintroduction
Example
DisplayupdatingintheFigureEditor:
AftereverychangeinaFigureElement'sstate,updatethedisplay..
AOPimplementation:•pointcuttoselecteverystate-changingmethodinFigureElementclasses.•`after'-advicewhichcallsdisplayupdatecode.
Question:whichdesignpatterncouldyouuse(insteadofAOP)?
CSC7336:AspectJ(JPGibson)November2017 20
AspectOrientedProgramming:abriefintroduction
Weaving:
Aprogramcalledanaspectweaverisusedtoweavetheadvicecodeintothemainprogramcode.
Often,butnotalways,joinpointmembershipinapointcutcanbedecidedstatically.=>noneedtoinsertcodeateverypossiblejoinpoint.
Modernsystems:•somedoweavingandcompilationinonestep•somecandoweavingatruntime(e.g.onJavabyte-code)
CSC7336:AspectJ(JPGibson)November2017 21
AspectOrientedProgramming:abriefintroduction
AspectJ
ExtensionsoftheJavalanguagefor•pointcuts•attachingadvice•staticcross-cutting
OriginallydevelopedatXeroxPARCFirstversionsinSpringof2000Hostedbyeclipse.orgsinceDecember2002
CSC7336:AspectJ(JPGibson)November2017 22
Installation
DownloadtheEclipseAJDTpluginfromhttp://eclipse.org/ajdt/downloads/
CSC7336:AspectJ(JPGibson)November2017 23
Installation
IfAspectJisalreadytherethenyoushouldnotneedtoaddit(butmayneedtoupdateit)
CSC7336:AspectJ(JPGibson)November2017 24
Installation
TryOutTheHelloWorldExampleDemo:
http://www.eclipse.org/ajdt/demos/
CSC7336:AspectJ(JPGibson)November2017 25
TryOutTheHelloWorldExampleDemo:
LetslookatthistogetherinEclipse
CSC7336:AspectJ(JPGibson)November2017 26
Installation
TryOutTheHelloWorldExampleDemo:
package p_helloworld;
public class Hello {
public static void main(String[] args) { sayHello(); }
public static void sayHello() { System.out.print("Hello"); }
}
CSC7336:AspectJ(JPGibson)November2017 27
Installation
TryOutTheHelloWorldExampleDemo:
package p_helloworld;
public aspect World {
pointcut greeting() : execution(* Hello.sayHello(..));
before() : greeting() { System.out.println(" World!"); }
}
CSC7336:AspectJ(JPGibson)November2017 28
Installation
Eclipseprovidesausefulcrossreferencewindow:
advisesHello.sayHello()
CSC7336:AspectJ(JPGibson)November2017 29
Experimentation
ExperimentwiththeDemo:whatwill/shouldhappenifyouaddanotheraspecttotheproject?
package p_helloworld;
public aspect MethodCounter {
int counter =0;
pointcut publicMethodCall() : execution(public * *.*(..)); pointcut afterMain(): execution(public * *.main(..));
after() returning() : publicMethodCall() { counter++; }
after() returning() : afterMain() { System.out.println("Method call counter = "+counter); } }
CSC7336:AspectJ(JPGibson)November2017 30
Experimentation
ExperimentwiththeDemo:canyouwriteanAspectthatwilltimetheexecutionofeachmethodcall?
package p_helloworld;
public aspect Profiler{
}
Thisshouldbeeasytocomplete.Istheon-linedocumentationgoodenough?
CSC7336:AspectJ(JPGibson)November2017 31
Experimentation
ExperimentwiththeDemo:canyouwriteanAspectthatwilltimetheexecutionofeachmethodcall?
World! Hello void p_helloworld.Hello.sayHello() took 26042892 nanoseconds
Method call counter = 2
void p_helloworld.Hello.main(String[]) took 32298490 nanoseconds
Whenyourunthecodewithall3aspectswoventogether,youshouldgetoutputofthefollowingform(moreorless):
CSC7336:AspectJ(JPGibson)November2017 32
AspectJ–somedetails
Reconsiderthefigureeditor
CSC7336:AspectJ(JPGibson)November2017 33
AspectJ–somedetails
Reconsiderthefigureeditor
Primitivepointcuts:
call(void Point.setX(int))
eachjoinpointthatisacalltoamethodthathasthesignaturevoidPoint.setX(int)
Alsoforinterfacesignatures:
call(void FigureElement.moveBy(int,int))
EachcalltothemoveBy(int,int)methodinaclassthatimplementsFigureElement
CSC7336:AspectJ(JPGibson)November2017 34
AspectJ–somedetails
Reconsiderthefigureeditor
Pointcutscanbejoinedusingbooleanoperators&&,||,!.
call(void Point.setX(int)) || call(void Point.setY(int))
callstothesetXandsetYmethodsofPoint.
Joinpointsfromdifferenttypespossible:
call(void FigureElement.moveBy(int,int)) || call(void Point.setX(int)) || call(void Point.setY(int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point))
Anycalltoastate-changingmethodinthegivenFigureElementclasses
CSC7336:AspectJ(JPGibson)November2017 35
AspectJ–somedetails
Reconsiderthefigureeditor
NamedPointcutsPointcutscanandshouldbedeclaredtogivethemaname:
pointcut stateChange() : call(void FigureElement.moveBy(int,int)) || call(void Point.setX(int)) || call(void Point.setY(int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point));
AnalogoustomethoddeclarationortypedefinC.
Afterdeclaration,stateChange()canbeusedwhereverapointcutisexpected.
CSC7336:AspectJ(JPGibson)November2017 36
AspectJ–somedetails
Reconsiderthefigureeditor
Wildcards
Methodsignaturescancontainwildcards:
call(void java.io.PrintStream.println(*))
anyPrintStreammethodnamedprintlnreturningvoidandtakingexactlyoneargumentofanytype.
call(public * Figure.*(..))
anypublicmethodinFigure.
call(public * Line.set*(..))
anymethodinLinewithanamestartingwithset.
CSC7336:AspectJ(JPGibson)November2017 37
AspectJ–somedetails
Reconsiderthefigureeditor
Example
Thepointcutfrombefore,usingwildcards:
pointcut stateChange() : call(void FigureElement.moveBy(int,int)) || call(* Point.set*(*)) || call(* Line.set*(*));
CSC7336:AspectJ(JPGibson)November2017 38
AspectJ–somedetails
Reconsiderthefigureeditor
AdviceinAspectJ
Advicecanbeattachedtojoinpoints:
before(): stateChange() { System.out.println("about to change state"); }
after() returning: stateChange() { System.out.println("just successfully changed state"); }
CSC7336:AspectJ(JPGibson)November2017 39
AspectJ–somedetails
//Aftereverystatechangingcall,updatethedisplay.
public aspect DisplayUpdating { pointcut stateChange() : call(void FigureElement.moveBy(int,int)) || call(* Point.set*(*)) || call(* Line.set*(*)); after() returning : stateChange() { Display.update(); } }
QUESTION:DoesthislooklikeagooduseofAspects?
CSC7336:AspectJ(JPGibson)November2017 40
AspectJ–somedetails
CSC7336:AspectJ(JPGibson)November2017 41
AspectJ–somedetails
CSC7336:AspectJ(JPGibson)November2017 42
AspectJ–somedetails
Example:DiagonalMoves
Defineapointcutformoveswithequaldxanddy.
pointcut diagHelp(int dx,int dy) : call(void FigureElement.moveBy(int,int)) && args(dx,dy) && if(dx==dy);
pointcut diagMove(int dxy) : diagHelp(dxy,int);
CSC7336:AspectJ(JPGibson)November2017 43
AspectJ–somedetails
AboutConditionals
AspectJspecification:
Thebooleanexpressionusedcanonlyaccessstaticmembers,variablesexposedbytheenclosingpointcutoradvice
Butstill...staticmethodsmaybecalled,whichmayhavesideeffects!
Question:whataretheconsequencesofthis?
CSC7336:AspectJ(JPGibson)November2017 44
AspectJ–somedetails
BeforeandAfter
`Before'advice:before(formal parameters) : Pointcut { . . . advice body. . . }
Theadvicebodygetsexecutedeverytimejustbeforetheprogramflowentersajoinpointmatchedbythepointcut.Theformalparametersreceivevaluesfromthepointcut
`After'advice:after(formal parameters) returning : Pointcut {...} Theadvicebodygetsexecutedeverytimejustaftertheprogramflowexitsajoinpointmatchedbythepointcutbyreturningnormally.
Capturereturnvalue:after(...) returning (int ret): Pointcut {...}
CSC7336:AspectJ(JPGibson)November2017 45
AspectJ–somedetails
Whataboutexceptions?
Adviceafterthrowinganexception:after(formal parameters) throwing : Pointcut {...}
Capturethrownexception:after(...) throwing (Exception e): Pointcut {...}
Matchnormalandabruptreturn:after(...) : Pointcut {...}
CSC7336:AspectJ(JPGibson)November2017 46
AspectJ–somedetails
AroundAdvice
Runadviceinsteadoforiginalcode:
Type around(. . . ) : . . . { . . . proceed(. . . ); . . . }
•runadvicebodyinsteadoforiginalcall,fieldaccess,methodbody,etc.•useproceedtousetheoriginaljoinpoint,ifneeded.
Hint:thismayhelpyoutowritethetimerAspectaskedforearlier
CSC7336:AspectJ(JPGibson)November2017 47
AspectJ–somedetails
TracingAspect(firsttry)
package tracing;
public aspect TraceAllCalls { pointcut pointsToTrace() : call(* *.*(..)) ;
before() : pointsToTrace() { System.err.println("Enter " + thisJoinPoint); }
after() : pointsToTrace() { System.err.println("Exit " + thisJoinPoint);
} }
QUESTION:Whereistheproblem?
CSC7336:AspectJ(JPGibson)November2017 48
AspectJ–somedetails
TracingAspect(firsttry)
package tracing; public aspect TraceAllCalls { pointcut pointsToTrace() : call(* *.*(..)) && !within(TraceAllCalls);
before() : pointsToTrace() { System.err.println("Enter " + thisJoinPoint); }
after() : pointsToTrace() { System.err.println("Exit " + thisJoinPoint); } }
QUESTION:Whydoweneedthewithin?
CSC7336:AspectJ(JPGibson)November2017 49
AspectJ–thingsyoushouldknowabout
ExceptionsinAdvice
Advicebodymaythrowexceptions:
before() : doingIO() { openOutputFile(); }
If openOutputFile() throws java.io.IOException: before() throws java.io.IOException : doingIO() { openOutputFile(); }
=>IOExceptionmustbedeclared/handledatallplaceswherepointcutapplies.
CSC7336:AspectJ(JPGibson)November2017 50
AspectJ–thingsyoushouldknowabout
Aspectsthrowingexceptions
Sometimes,anaspectcanchangethebehaviourofmethods,sothatnewcheckedexceptionsarethrown:
•Addsynchronization:InterruptedException•Executecallsremotely:RemoteException
=>Twopossibilities:•catchandhandleexceptiondirectlyinadvice.Mightnotbeappropriate.•passexceptionoutofadvice.Needslotsofdeclarations.
CSC7336:AspectJ(JPGibson)November2017 51
AspectJ–thingsyoushouldknowabout
CSC7336:AspectJ(JPGibson)November2017 52
AspectJ–thingsyoushouldknowabout
AspectPrecedence(cont.)
Syntaxtodeclareaspectprecedence:
declare precedence : TypePattern1, TypePattern2, . . . ;
Mayoccurinanyaspect.Saysthatanythingmatchingtypepattern1hashigherprecedencethananythingmatchingtypepattern2,etc.
aspect CyclicPrecedence { declare precedence : AspectA, AspectB; declare precedence : AspectB, AspectA; }
OKiffaspectssharenojoinpoints.
CSC7336:AspectJ(JPGibson)November2017 53
AspectJ–thingsyoushouldknowabout
AspectPrecedence(cont.)
Ifnotdeclared,implicitruleforinheritance:
IfAspectAextendsAspectB,thenAspectAhashigherpriority.
⇒possibletooverruleadvicefromsuper-aspect.
Ifstillnotdeclared,implicitruleforadvicewithinoneaspect:•Ifeitherareafteradvice,thentheonethatappearslaterintheaspecthasprecedenceovertheonethatappearsearlier.•Otherwise,thentheonethatappearsearlierintheaspecthasprecedenceovertheonethatappearslater.
=>firstdosomethinginthesameorderastheyappearinthesource
CSC7336:AspectJ(JPGibson)November2017 54
AspectJ–thingsyoushouldknowabout
AbstractAspects
Reminder:aspectscan•extendclasses•extendabstractaspects•implementinterfaces
Abstractaspectsmaycontain
•abstractmethods,likeabstractclasses•abstractpointcutdeclarations
Abstractaspectsarethekeytowritingreusableaspects.
CSC7336:AspectJ(JPGibson)November2017 55
AspectJ–thingsyoushouldknowabout
AspectInstantiation
Atruntime,aspectshavefieldslikeobjects.
Whendotheygetinstantiated?Usually:Instantiateanaspectonceperprogramexecution.
aspect Id {...} aspect Id issingleton {...}
Implementedassingleton=>staticfieldinaspectclass.
NOTE:ThingsareactuallymuchmorecomplicatedwhenweconsiderallthedifferentwaysinwhichJavaobjects(includingAspects)areinstantiated
CSC7336:AspectJ(JPGibson)November2017 56
AspectJ–thingsyoushouldknowabout
PrivilegedAspects
Usually,advicecodehasnoaccesstoprivatemembersofadvisedclasses.
(Notethatmatchinginpointcutsdoesseeprivatemembers)
Buttheprivilegedkeywordcanhelp:
privileged public aspect A { before(MyFriend f) : this(f) && ... { System.out.println("My best friends secret: " + f._privateField); } }
CSC7336:AspectJ(JPGibson)November2017 57
AspectJ–profilingproblem
Returntotheprofilingproblemwelookedatinpreviousclass
TODO:Implement3ormoreinterestingprofilingaspectsandtestondifferentprograms
PracticalWorkForNextClass:InvariantTesting
Writeanaspectthatteststheinvariantofaclasseverytimeamethodisexecuted,andwritestoaninvariantlogfilewhetherthetestpassesorfails.
top related