Top Banner
CSC7336: AspectJ (J P Gibson) November 2017 1 Aspects in AspectJ Motivation Aspect Oriented Programming: a brief introduction to terminology Installation Experimentation AspectJ – some details AspectJ – things you should know about but we dont have time to cover in detail AspectJ – profiling problem
57

Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

May 25, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 1

AspectsinAspectJ

•Motivation•AspectOrientedProgramming:abriefintroductiontoterminology•Installation•Experimentation•AspectJ–somedetails•AspectJ–thingsyoushouldknowaboutbutwedonthavetimetocoverindetail•AspectJ–profilingproblem

Page 2: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 2

Motivation

“Abilityiswhatyou'recapableofdoing.Motivationdetermineswhatyoudo.Attitudedetermineshowwellyoudoit.”LouHoltz

Page 3: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 3

Motivation

Evenwelldesignedsystemshaveaspectsthatcutacrossalargenumberofthecomponents

Forexample,considerApacheTomcat,wherecertainaspectsoffunctionalityare:

•XMLparsing•URLpatternmatching•Logging•SessionManagement

Question:whichofthesearewelllocalised?

Page 4: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 4

Motivation

XMLparsing

URLpatternmatching

Logging

SessionManagement:differenttypes

•ApplicationSession•ServerSession•StandardSession•Managers

Sothecodeforeachsessionstageshouldbewelllocalised?

Page 5: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 5

Motivation

SessionExpiration:codeisdistributedthroughlotsofdifferentclasses

Page 6: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 6

Motivation

SessionExpiration:abetterdesign?

Unfortunately,ifwedothiswewillhavetocompromisebyredistributingpreviouslylocalisedcode.

Page 7: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 7

Motivation

SeparationofConcernsisatime-honouredprincipleofSoftwaredesign

D.Parnas.OntheCriteriatoBeUsedinDecomposingSystemsintoModules.Comm.ACM15,12(December1972),1053-1058.

Designprinciplesfordecomposition:•Information-hidingmodules•Identifydesigndecisionsthatarelikelytochange.•Isolatetheseinseparatemodules(separationofconcerns)

Page 8: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 8

Motivation

Cross-Cutting Concerns

Inthemotivation,

•XMLparsingandURLpatternmatchingfittheclasshierarchy,•LoggingandSessionManagementdonot.

Across-cuttingconcernisonethatneedstobeaddressedinmorethanoneofthemodulesinthehierarchicalstructureofthesoftware.

Cross-cuttingconcernsarealsocalledaspects.

Whatisanaspectdependsonthechosendecomposition!

Page 9: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 9

Motivation

ProblemswithCross-CuttingConcerns

Cross-cuttingconcernsposeproblemsforstandard,e.g.OO,programmingtechniques:

•hardanderror-pronetointroduceinanexistingsystem•hardtochangeafterwards•hardtounderstand/explaintonewcomers

Cross-cuttingimplementationofcross-cuttingconcernsdoesnotprovideseparationofconcerns.

Page 10: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 10

Motivation

Solutions

Possibletreatmentofcross-cuttingconcerns:

Refactorthemaway.Changethemodulehierarchysothattheaspectbecomesmodular,oftenthroughapplicationofadequatedesignpatterns.

But:•oftenperformancepenaltiesthroughindirection•oftenleavessomecross-cuttingboiler-plate•can'thopetocaptureallaspects

Page 11: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 11

AspectOrientedProgramming:abriefintroduction

AprogrammingmethodologyiscalledAspect-Orientedifitprovidespossibilitiestocleanlyseparateconcernsthatwouldotherwisebecross-cutting.

TherearevariousAspect-Orientedmethods.Theydifferinthekindsofaspectstheycanaddressandinthewaysaspectsandtheirrelationtothechosenhierarchicaldecompositionareexpressed.

Page 12: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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

Page 13: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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

Page 14: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 14

AspectOrientedProgramming:abriefintroduction

CodeExample:FigureEditor(fromhttp://eclipse.org/aspectj/doc/released/progguide/)

Page 15: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 15

AspectOrientedProgramming:abriefintroductionCodeExample:FigureEditor

A join point is a point in the control flow of a program

Page 16: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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

Page 17: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 17

AspectOrientedProgramming:abriefintroduction

Apointcutdesignatesasetofjoinpointsforanyprogramexecution.

Atexecution,anyjoinpointmayormaynotbeselectedbyapointcut.

Examples:•allcallstopublicmethodsofthePointclass•everyexecutionofaconstructorwithoneintargument•everywriteaccesstoapublicfield

Membershipofajoinpointmaybedeterminedatruntime

Page 18: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 18

AspectOrientedProgramming:abriefintroduction

Advice

Adviceiscodethatshouldbeinsertedbefore,afteroreveninsteadofexistingcodeatsomesetofjoinpoints.

`Mainstream'AOP:

•Designatesetsofjoinpointsusingsomespecificationlanguageforpointcuts.•Declareadvicetobeexecutedbefore/after/insteadofthecalls/methodexecutions/fieldaccessesetc.selectedbythepointcut.

Page 19: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 19

AspectOrientedProgramming:abriefintroduction

Example

DisplayupdatingintheFigureEditor:

AftereverychangeinaFigureElement'sstate,updatethedisplay..

AOPimplementation:•pointcuttoselecteverystate-changingmethodinFigureElementclasses.•`after'-advicewhichcallsdisplayupdatecode.

Question:whichdesignpatterncouldyouuse(insteadofAOP)?

Page 20: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 20

AspectOrientedProgramming:abriefintroduction

Weaving:

Aprogramcalledanaspectweaverisusedtoweavetheadvicecodeintothemainprogramcode.

Often,butnotalways,joinpointmembershipinapointcutcanbedecidedstatically.=>noneedtoinsertcodeateverypossiblejoinpoint.

Modernsystems:•somedoweavingandcompilationinonestep•somecandoweavingatruntime(e.g.onJavabyte-code)

Page 21: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 21

AspectOrientedProgramming:abriefintroduction

AspectJ

ExtensionsoftheJavalanguagefor•pointcuts•attachingadvice•staticcross-cutting

OriginallydevelopedatXeroxPARCFirstversionsinSpringof2000Hostedbyeclipse.orgsinceDecember2002

Page 22: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 22

Installation

DownloadtheEclipseAJDTpluginfromhttp://eclipse.org/ajdt/downloads/

Page 23: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 23

Installation

IfAspectJisalreadytherethenyoushouldnotneedtoaddit(butmayneedtoupdateit)

Page 24: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 24

Installation

TryOutTheHelloWorldExampleDemo:

http://www.eclipse.org/ajdt/demos/

Page 25: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 25

TryOutTheHelloWorldExampleDemo:

LetslookatthistogetherinEclipse

Page 26: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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"); }

}

Page 27: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 27

Installation

TryOutTheHelloWorldExampleDemo:

package p_helloworld;

public aspect World {

pointcut greeting() : execution(* Hello.sayHello(..));

before() : greeting() { System.out.println(" World!"); }

}

Page 28: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 28

Installation

Eclipseprovidesausefulcrossreferencewindow:

advisesHello.sayHello()

Page 29: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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); } }

Page 30: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 30

Experimentation

ExperimentwiththeDemo:canyouwriteanAspectthatwilltimetheexecutionofeachmethodcall?

package p_helloworld;

public aspect Profiler{

}

Thisshouldbeeasytocomplete.Istheon-linedocumentationgoodenough?

Page 31: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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):

Page 32: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 32

AspectJ–somedetails

Reconsiderthefigureeditor

Page 33: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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

Page 34: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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

Page 35: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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.

Page 36: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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.

Page 37: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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*(*));

Page 38: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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"); }

Page 39: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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?

Page 40: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 40

AspectJ–somedetails

Page 41: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 41

AspectJ–somedetails

Page 42: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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);

Page 43: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 43

AspectJ–somedetails

AboutConditionals

AspectJspecification:

Thebooleanexpressionusedcanonlyaccessstaticmembers,variablesexposedbytheenclosingpointcutoradvice

Butstill...staticmethodsmaybecalled,whichmayhavesideeffects!

Question:whataretheconsequencesofthis?

Page 44: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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 {...}

Page 45: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 45

AspectJ–somedetails

Whataboutexceptions?

Adviceafterthrowinganexception:after(formal parameters) throwing : Pointcut {...}

Capturethrownexception:after(...) throwing (Exception e): Pointcut {...}

Matchnormalandabruptreturn:after(...) : Pointcut {...}

Page 46: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 46

AspectJ–somedetails

AroundAdvice

Runadviceinsteadoforiginalcode:

Type around(. . . ) : . . . { . . . proceed(. . . ); . . . }

•runadvicebodyinsteadoforiginalcall,fieldaccess,methodbody,etc.•useproceedtousetheoriginaljoinpoint,ifneeded.

Hint:thismayhelpyoutowritethetimerAspectaskedforearlier

Page 47: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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?

Page 48: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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?

Page 49: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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.

Page 50: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 50

AspectJ–thingsyoushouldknowabout

Aspectsthrowingexceptions

Sometimes,anaspectcanchangethebehaviourofmethods,sothatnewcheckedexceptionsarethrown:

•Addsynchronization:InterruptedException•Executecallsremotely:RemoteException

=>Twopossibilities:•catchandhandleexceptiondirectlyinadvice.Mightnotbeappropriate.•passexceptionoutofadvice.Needslotsofdeclarations.

Page 51: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 51

AspectJ–thingsyoushouldknowabout

Page 52: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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.

Page 53: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 53

AspectJ–thingsyoushouldknowabout

AspectPrecedence(cont.)

Ifnotdeclared,implicitruleforinheritance:

IfAspectAextendsAspectB,thenAspectAhashigherpriority.

⇒possibletooverruleadvicefromsuper-aspect.

Ifstillnotdeclared,implicitruleforadvicewithinoneaspect:•Ifeitherareafteradvice,thentheonethatappearslaterintheaspecthasprecedenceovertheonethatappearsearlier.•Otherwise,thentheonethatappearsearlierintheaspecthasprecedenceovertheonethatappearslater.

=>firstdosomethinginthesameorderastheyappearinthesource

Page 54: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 54

AspectJ–thingsyoushouldknowabout

AbstractAspects

Reminder:aspectscan•extendclasses•extendabstractaspects•implementinterfaces

Abstractaspectsmaycontain

•abstractmethods,likeabstractclasses•abstractpointcutdeclarations

Abstractaspectsarethekeytowritingreusableaspects.

Page 55: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 55

AspectJ–thingsyoushouldknowabout

AspectInstantiation

Atruntime,aspectshavefieldslikeobjects.

Whendotheygetinstantiated?Usually:Instantiateanaspectonceperprogramexecution.

aspect Id {...} aspect Id issingleton {...}

Implementedassingleton=>staticfieldinaspectclass.

NOTE:ThingsareactuallymuchmorecomplicatedwhenweconsiderallthedifferentwaysinwhichJavaobjects(includingAspects)areinstantiated

Page 56: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

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); } }

Page 57: Aspects in AspectJ - Télécom SudParisgibson/Teaching/CSC7336/L2-AspectJ.pdf · November 2017 CSC7336: AspectJ (J P Gibson) 1 Aspects in AspectJ •Motivation •Aspect Oriented

CSC7336:AspectJ(JPGibson)November2017 57

AspectJ–profilingproblem

Returntotheprofilingproblemwelookedatinpreviousclass

TODO:Implement3ormoreinterestingprofilingaspectsandtestondifferentprograms

PracticalWorkForNextClass:InvariantTesting

Writeanaspectthatteststheinvariantofaclasseverytimeamethodisexecuted,andwritestoaninvariantlogfilewhetherthetestpassesorfails.