470 likes | 597 Views
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. Overview. Motivation
E N D
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
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 CASCON '04
XML parsing in org.apache.tomcat red shows relevant lines of code nicely fits in one box Good modularity XML parsing CASCON '04
URL pattern matching in org.apache.tomcat red shows relevant lines of code nicely fits in two boxes (using inheritance) Good modularity URL pattern matching CASCON '04
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 Bad modularity logging is not modularized CASCON '04
SessionInterceptor requestMap(request) beforeBody(req, resp) ... Session getAttribute(name) setAttribute(name, val) invalidate() ... Bad modularity explained Session-tracking is not modularized HTTPRequest • Scattering: session-tracking implemented in multiple places • Tangling: One place implements multiple high-level concepts. E.g. HTTPResponse implements session-tracking and I/O. getCookies() getRequestURI()(doc) getSession()getRequestedSessionId() ... HTTPResponse getRequest() setContentType(contentType) getOutptutStream()setSessionId(id) ... Servlet CASCON '04
logging, security, optimizations 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 CASCON '04
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 CASCON '04
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 CASCON '04
Display * Figure FigureElement moveBy(int, int) makePoint(..)makeLine(..) Point Line 2 getX()getY()setX(int)setY(int)moveBy(int, int) getP1()getP2()setP1(Point)setP2(Point)moveBy(int, int) A simple figure editor • Whenever a FigureElement changes location, the display must be updated CASCON '04
Without AspectJ DisplayUpdating 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(); } } 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(); } } • No locus of Display updating • Difficult to change • Scattered and tangled CASCON '04
With AspectJ DisplayUpdating 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(); } } 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(); } } 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(); } } CASCON '04
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 CASCON '04
a method call a method execution a method execution Joinpoints class Point { void moveBy(int dx, int dy) { x += dx; y += dy; } } class SpecialPoint extends Point { void moveBy(int dx, int dy) {…} } 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) {…} } aLine.moveBy(2, 2); aLine Circles indicates joinpoints, nodes in dynamic call graph. Coloured code indicates corresponding joinpoint “shadows”. dispatch aPoint dispatch returning or throwing returning or throwing returning or throwing CASCON '04
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; CASCON '04
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)) CASCON '04
Named pointcuts Pointcut descriptor (PCD) Pointcut 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 CASCON '04
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) CASCON '04
a Line Advice • 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(); } } CASCON '04
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 CASCON '04
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(FigureElementfigureElement) returning: move(figureElement) { Display.update(figureElement); } } CASCON '04
args: picking out arguments 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; } 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; } } CASCON '04
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(FigureEditorfigureEditor) returning: move(figureEditor) { Display.update(figureEditor); } } CASCON '04
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()); • } • } CASCON '04
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 CASCON '04
withincode class Point implements FigureElement { void moveBy(int dx, int dy) { x += dx; y += dy; } ... } setX(getX() + dx); setY(getY() + dy); public aspect SetterEnforcement { pointcut notUsingSetter(): set(* *.*) && !withincode(* *.set*(..)); declare error: notUsingSetter(): "Use setter method outside of setter methods"; } within(ClassName) can be used to loosen the restriction CASCON '04
cflow class Point { void moveBy(int x, int y) { setX(getX()+x); Display.update(); setY(getY()+y); Display.update(); } ... } p.moveBy(2, 4); 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. CASCON '04
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 CASCON '04
before before proceeding at join point after returning a value at join point after throwinga throwable at join point after returning at join point either way aroundon arrival at join point gets explicit control over when&if program proceeds Types of advice CASCON '04
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 after throwing advice aspect PublicErrorLogging { pointcut publicInterface(): call(public * com.bigboxco..*.*(..)); after() throwing (Error e): publicInterface() { Logger.warning(e); } } CASCON '04
around advice 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); } ... } 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)); } } CASCON '04
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 CASCON '04
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()); aspect DisplayUpdating { private Display FigureElement.display; static void setDisplay(FigureElement fe, Display d) { fe.display = d; } pointcut move(FigureElement figElt): <as before>; after(FigureElement fe): move(fe) { fe.display.update(fe); } } DisplayUpdating.aspectOf(). setDisplay(p, new Display()); CASCON '04
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 CASCON '04
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 AspectJ applied to a large middleware system • 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 CASCON '04
Other applications • GUI • Design patterns • Distributed systems • Data marshalling • Synchronization • Concurrency • System-level software • OS kernels • Debugging and testing • Monitoring • Optimization • Loop fusion CASCON '04
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 CASCON '04
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 CASCON '04
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? CASCON '04
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. void repairScreen() { displayRectangle.set(0, 0, WIDTH, LENGTH); Display.update(); } Should Display.update() 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? CASCON '04
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(putInToolBar(Action)) && args(action) { register(action); } Perspective: GUI developer after(action): call(register(Action)) && args(action) { putInToolBar(action); } Perspective: extensions developer • Although AspectJ permits only one perspective (asymmetric), languages like HyperJ permit multiple perspectives (symmetric) CASCON '04
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 CASCON '04
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 CASCON '04
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 CASCON '04
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 CASCON '04
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? CASCON '04
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! CASCON '04