Presentation is loading. Please wait.

Presentation is loading. Please wait.

An Introduction to AOP Original slides developed by Julie Waterhouse and Mik Kersten for OOPSLA 2004 AspectJ Tutorial ( kerstens.org/mik/publications/aspectj-

Similar presentations


Presentation on theme: "An Introduction to AOP Original slides developed by Julie Waterhouse and Mik Kersten for OOPSLA 2004 AspectJ Tutorial ( kerstens.org/mik/publications/aspectj-"— Presentation transcript:

1 An Introduction to AOP Original slides developed by Julie Waterhouse and Mik Kersten for OOPSLA 2004 AspectJ Tutorial ( kerstens.org/mik/publications/aspectj- tutorial-oopsla2004.ppt) Adapted by Peter Kim for Spring 2007 SE2 classes, University of Waterloo

2 CASCON '04 2 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

3 CASCON '04 3 Good modularity XML parsing in org.apache.tomcat –red shows relevant lines of code –nicely fits in one box XML parsing

4 CASCON '04 4 Good modularity URL pattern matching in org.apache.tomcat –red shows relevant lines of code –nicely fits in two boxes (using inheritance) URL pattern matching

5 CASCON '04 5 Bad modularity logging in org.apache.tomcat –red shows lines of code that handle logging –not in just one place –not even in a small number of places logging is not modularized

6 CASCON '04 6 getCookies() getRequestURI()(doc) getSession() getRequestedSessionId()... Bad modularity explained HTTPRequest HTTPResponse Servlet getRequest() setContentType(contentType) getOutptutStream() setSessionId(id)... SessionInterceptor requestMap(request) beforeBody(req, resp)... Session getAttribute(name) setAttribute(name, val) invalidate()... Session-tracking is not modularized Scattering: session- tracking implemented in multiple places Tangling: One place implements multiple high- level concepts. E.g. HTTPResponse implements session- tracking and I/O.

7 CASCON '04 7 Problem of modularizing crosscutting concerns Critical aspects of large systems don’t fit in traditional modules –Logging, error handling –Synchronization –Security –Power management –Memory management –Performance optimizations Tangled code has a cost –Difficult to understand –Difficult to change –Increases with size of system –Maintenance costs are huge Good programmers work hard to get rid of tangled code –Development and maintenance headaches logging, security, optimizations

8 CASCON '04 8 Solution: Aspect-Oriented Programming Crosscutting is inherent in complex systems, but they have –have a clear purpose –have a natural structure defined by a set of methods, module boundary crossings, points of resource utilization, lines of dataflow… So, let’s capture the structure of crosscutting concerns explicitly... –in a modular way –with linguistic and tool support Aspects are –well-modularized crosscutting concerns Aspect-Oriented Software Development: AO support throughout lifecycle

9 CASCON '04 9 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

10 CASCON '04 10 A simple figure editor Display * 2 Point getX() getY() setX(int) setY(int) moveBy(int, int) Line getP1() getP2() setP1(Point) setP2(Point) moveBy(int, int) Figure makePoint(..) makeLine(..) FigureElement moveBy(int, int) Whenever a FigureElement changes location, the display must be updated

11 CASCON '04 11 Without AspectJ DisplayUpdating class Line implements FigureElement { private Point p1, p2; Point getP1() { return p1; } Point getP2() { return p2; } void setP1(Point p1) { this.p1 = p1; Display.update(); } void setP2(Point p2) { this.p2 = p2; Display.update(); } void moveBy(int dx, int dy) { p1.x += dx; p1.y += dy; p2.x += dx; p2.y += dy; Display.update(); } class Point implements FigureElement { private int x = 0, y = 0; int getX() { return x; } int getY() { return y; } void setX(int x) { this.x = x; Display.update(); } void setY(int y) { this.y = y; Display.update(); } void moveBy(int dx, int dy) { x += dx; y += dy; Display.update(); } No locus of Display updating –Difficult to change –Scattered and tangled

12 CASCON '04 12 With AspectJ DisplayUpdating class Line implements FigureElement { private Point p1, p2; Point getP1() { return p1; } Point getP2() { return p2; } void setP1(Point p1) { this.p1 = p1; Display.update(); } void setP2(Point p2) { this.p2 = p2; Display.update(); } void moveBy(int dx, int dy) { p1.x += dx; p1.y += dy; p2.x += dx; p2.y += dy; Display.update(); } class Point implements FigureElement { private int x = 0, y = 0; int getX() { return x; } int getY() { return y; } void setX(int x) { this.x = x; Display.update(); } void setY(int y) { this.y = y; Display.update(); } void moveBy(int dx, int dy) { x += dx; y += dy; Display.update(); } aspect DisplayUpdating { pointcut move(): call(void FigureElement. moveBy(int, int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)) || call(void Point.setX(int)) || call(void Point.setY(int)); after() returning: move() { Display.update(); }

13 CASCON '04 13 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

14 CASCON '04 14 aLine aPoint Joinpoints returning or throwing dispatch a method call returning or throwing a method execution returning or throwing a method execution aLine.moveBy(2, 2); class Line …{ void moveBy(int dx, int dy) { p1.moveBy(dx, dy); p2.moveBy(dx, dy); } class SpecialLine extends Line { void moveBy(int dx, int dy) {…} } class Point { void moveBy(int dx, int dy) { x += dx; y += dy; } class SpecialPoint extends Point { void moveBy(int dx, int dy) {…} } Circles indicates joinpoints, nodes in dynamic call graph. Coloured code indicates corresponding joinpoint “shadows”.

15 CASCON '04 15 Pointcuts A pointcut is a predicate (query) on joinpoints –Matches (or excludes) join points –Optionally pulls out information available at joinpoint (e.g. receiver, caller, function arguments) Primitive pointcut examples –call(void FigureElement.moveBy(int, int)) aLine.moveBy(3, 3); –set(int Point.x) / get(int Point.x) p1.x = p1.x + dx;

16 CASCON '04 16 Pointcut composition Pointcuts compose using ||, &&, !: –call(void FigureElement.moveBy(int, int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)) || call(void Point.setX(int)) || call(void Point.setY(int))

17 CASCON '04 17 Named pointcuts pointcut move(): call(void FigureElement.moveBy(int, int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)) || call(void Point.setX(int)) || call(void Point.setY(int)); “move” is an abstraction capturing characteristic runtime events Pointcut Pointcut descriptor (PCD)

18 CASCON '04 18 Pointcut wildcards pointcut move(): call(void FigureElement.moveBy(int, int)) || call(void Line.set*(..)) || call(void Point.set*(..)); Wildcards should be used with caution: unintended join points may be captured (e.g. a new method introduced “setID” may have nothing to do with “move” pointcut)

19 CASCON '04 19 Advice a Line Specifies action to take after or before computation under join points after advice specifies action to take after each “move” join point aspect DisplayUpdating { pointcut move(): call(void FigureElement. moveBy(int, int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)) || call(void Point.setX(int)) || call(void Point.setY(int)); after() returning: move() { Display.update(); }

20 CASCON '04 20 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

21 CASCON '04 21 target: picking out receiver aLine.move(3, 3); Display.update(aLine); aPoint.setX(3); Display.update(aPoint); aspect Logging { pointcut move(FigureElement figureElement): (call(void FigureElement.moveBy(int, int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)) || call(void Point.setX(int)) || call(void Point.setY(int))) && target(figureElement); after(FigureElement figureElement) returning: move(figureElement) { Display.update(figureElement); }

22 CASCON '04 22 args: picking out arguments aspect PointBoundsPreCondition { before(int newX): call(void Point.setX(int)) && args(newX) { assert newX >= MIN_X; assert newX <= MAX_X; } before(int newY): call(void Point.setY(int)) && args(newY) { assert newY >= MIN_Y; assert newY <= MAX_Y; } void Point.setX(int x) { if(x >= MIN_X && x <= MAX_X) this.x = x; } void Point.setY(int y) { if(y >= MIN_Y && y <= MAX_Y) this.y = y; }

23 CASCON '04 23 this: picking out caller class FigureEditor { void animate() { aLine.move(3, 3); Display.update(this); … } aspect Logging { pointcut move(FigureEditor figureEditor): (call(void FigureElement.moveBy(int, int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)) || call(void Point.setX(int)) || call(void Point.setY(int))) && this(figureEditor); after(FigureEditor figureEditor) returning: move(figureEditor) { Display.update(figureEditor); }

24 CASCON '04 24 thisJoinPoint: join point reflection void Point.setX(int x) { System.out.println (“Point.setX(“ + x + “)”); this.x = x; } void Line.moveBy(int dx, int dy) { System.out.println( (“Line.moveBy(” + dx + “, “ + dy + “)”); p1.moveBy(dx); p2.moveBy(dy); } aspect Logging { pointcut move(): call(void FigureElement.moveBy(int, int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)) || call(void Point.setX(int)) || call(void Point.setY(int)); before(): move() { System.out.println (thisJoinPoint.getSignature()); System.out.println (thisJoinPoint.getArguments()); }

25 CASCON '04 25 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

26 CASCON '04 26 withincode class Point implements FigureElement { void moveBy(int dx, int dy) { x += dx; y += dy; }... } public aspect SetterEnforcement { pointcut notUsingSetter(): set(* *.*) && !withincode(* *.set*(..)); declare error: notUsingSetter(): "Use setter method outside of setter methods"; } setX(getX() + dx); setY(getY() + dy); within(ClassName) can be used to loosen the restriction

27 CASCON '04 27 cflow p.moveBy(2, 4); Display.update(); class Point { void moveBy(int x, int y) { setX(getX()+x); Display.update(); setY(getY()+y); Display.update(); }... } Update is being called three times when it should be only called once! We only want the top- level moves to be updated. aspect DisplayUpdating { pointcut move(): call(void FigureElement. moveBy(int, int)) ||... call(void Point.setX(int)) || call(void Point.setY(int)); pointcut topLevelMove(): move() && !cflowbelow(move()); after() returning: topLevelMove() { Display.update(); } Only moves that are not under the control flow of another move are advised.

28 CASCON '04 28 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

29 CASCON '04 29 Types of advice before before proceeding at join point after returning a value at join point after throwing a throwable at join point after returning at join point either way around on arrival at join point gets explicit control over when&if program proceeds

30 CASCON '04 30 after throwing advice consider code maintenance another programmer adds a public method i.e. extends public interface – this code will still work another programmer reads this code “what’s really going on” is explicit aspect PublicErrorLogging { pointcut publicInterface(): call(public * com.bigboxco..*.*(..)); after() throwing (Error e): publicInterface() { Logger.warning(e); }

31 CASCON '04 31 around advice aspect BoundsEnforcement { void around(int value): call(void Point.set*(int)) && args(value) { proceed( clip(newValue, MIN_COORDINATE, MAX_COORDINATE) ); } private int clip(int val, int min, int max) { return Math.max(min, Math.min(max, val)); } class Point { final static int MAX_COORDINATE = …; final static int MIN_COORDINATE = …; void setX(int x) { this.x = clip(x); } void setY(int y) { this.y = clip(y); }... }

32 CASCON '04 32 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

33 CASCON '04 33 aspect DisplayUpdating { private Display FigureElement.display; static void setDisplay(FigureElement fe, Display d) { fe.display = d; } pointcut move(FigureElement figElt): ; after(FigureElement fe): move(fe) { fe.display.update(fe); } Inter-type declaration: one Display per FigureElement class FigureElement { Display display; void setDisplay(Display display) {…} Display getDisplay(Display display) {…} void moveBy(int dx, int dy) {} } class Point extends FigureElement { void setX(int x) {... display.update(this); } Point p = new Point(); p.setDisplay(new Display()); DisplayUpdating.aspectOf(). setDisplay(p, new Display());

34 CASCON '04 34 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

35 CASCON '04 35 Java code base with 10,000 files and 500 developers AspectJ captured logging, error handling, and profiling policies –Packaged as extension to Java language –Compatible with existing code base and platform AspectJ applied to a large middleware system existing policy implementations affect every file –5-30 page policy documents –applied by developers affect every developer –must understand policy document repeat for new code assets awkward to support variants –complicates product line don’t even think about changing the policy policies implemented with AspectJ one reusable crosscutting module –policy captured explicitly –applies policy uniformly for all time written by central team –no burden on other 492 developers automatically applied to new code easy plug and unplug –simplifies product line issues changes to policy happen in one place

36 CASCON '04 36 Other applications GUI –Design patterns Distributed systems –Data marshalling –Synchronization –Concurrency System-level software –OS kernels Debugging and testing Monitoring Optimization –Loop fusion

37 CASCON '04 37 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

38 CASCON '04 38 Obliviousness Ideally, application code should evolve independently of aspects that apply to it and vice versa // evolution makes computation offline, not requiring an update window.setVisible(false); … line.moveBy(dx, dy); Display.update(); // woven by aspect In reality, understanding evolutionary relationship between between aspect and application code (i.e. how does change in one affect the other) is more practical –E.g. Tool support can notify aspect when application code changes and application code when aspect changes

39 CASCON '04 39 Quantification Eliminating redundancy is one of the biggest benefits of AOP –So redundancy must exist Homogeneous advice: uniform (e.g. Display.update()) to all joinpoints –But how often does this really happen? Heterogeneous advice: depends on context (e.g. repainting a large image different from repainting a piece of text) –Unless commonalities (redundancy) can be found between multiple joinpoints, an aspect that applies to these multiple joinpoints cannot be written E.g. Without thisJoinPoint, impossible to write a quantifying aspect that logs a method call name –By understanding how to group joinpoints more meaningfully, we can make aspects more applicable But can an aspect apply to a single join point?

40 CASCON '04 40 Separation of concerns Another major benefit of AOP is separation of secondary concerns from the primary concern void animate() { line1.moveBy(2, 2); Display.update(); line2.moveBy(3, 4); Display.update(); } Display.update() should be separated. But is Display.update() always a secondary concern? It seems to be an integral part of repairing screen (repainting) Are aspects just about physical separation? void repairScreen() { displayRectangle.set(0, 0, WIDTH, LENGTH); Display.update(); } Should Display.update() be separated?

41 CASCON '04 41 Viewpoints AOP has a strong connection to viewpoints in software engineering E.g. when an Action is registered for extension, it must be also placed in a toolbar and vice versa after(action): call(register(Action)) && args(action) { putInToolBar(action); } Perspective: extensions developer after(action): call(putInToolBar(Action)) && args(action) { register(action); } Perspective: GUI developer Although AspectJ permits only one perspective (asymmetric), languages like HyperJ permit multiple perspectives (symmetric)

42 CASCON '04 42 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

43 CASCON '04 43 AOP vs. metaprogramming AOP has strong roots in metaprogramming, but is quite different from it Metaprogramming: focus on representing code as manipulative data –E.g. “upon execution of methods called set*, execute the method Display.update” AOP: focus on runtime events –E.g. “whenever change occurs, update display” –thisJoinPoint is the closest thing to metaprogramming

44 CASCON '04 44 AOP vs. program transformation An aspect transforms a program without “Display.update” to a program with it But imagining how the transformed program would look is like imagining what method would be dispatched for each method call –This defeats essential features of AOP (quantification) and OOP (polymorphism) Another danger is that there are infinitely many ways to transform an AOP program into an OO program –How transformation occurs is the business of the compiler, not the developer One should think of AOP in terms of meaningful pointcuts and advices

45 CASCON '04 45 Overview Motivation AspectJ language –First example –Basic language constructs –Joinpoint data retrieval –Restrictive mechanisms –Types of advice –Inter-type declarations Applications Key ideas Misconceptions State of the art

46 CASCON '04 46 Research in AOP Application –When is AOP more suitable than other techniques? Mining and refactoring –Find crosscutting concerns in normal applications and transform them into aspects Expressivity of languages –E.g. What does “after” mean? Immediately after or sometime after? When a file is opened, it must be closed after. Performance –AOP programs are slower due to weaving overhead. How can we advance compiler technology here? Early aspects –Like objects, do aspects exist at other abstraction levels, such as requirements and design artifacts? Generative Software Development –How can aspects be used to model product lines from requirements to code?

47 CASCON '04 47 Conclusion Aspects modularize crosscutting concerns that cannot be captured cleanly using primary constructs Aspects specify what actions to take (advice) “whenever” something happens (pointcut) Aspects eliminate redundancy, separate concerns, and provide different viewpoints on the same program Aspects are abstractions like objects, rather than metaprogramming or program transformation mechanisms There is exciting research going on in AOP (for over 10 years now) so join in!


Download ppt "An Introduction to AOP Original slides developed by Julie Waterhouse and Mik Kersten for OOPSLA 2004 AspectJ Tutorial ( kerstens.org/mik/publications/aspectj-"

Similar presentations


Ads by Google