aspect-oriented programming david talby. what is it? a new addition to the world of programming new...

40
Aspect-Oriented Aspect-Oriented Programming Programming David Talby David Talby

Post on 22-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Aspect-Oriented Aspect-Oriented ProgrammingProgramming

David TalbyDavid Talby

What is it?What is it?

A new addition to the world of programmingA new addition to the world of programming New concepts & language constructsNew concepts & language constructs New tools (aspect compiler, browser, debugger)New tools (aspect compiler, browser, debugger) Many examples & patterns of practical useMany examples & patterns of practical use A lot of hypeA lot of hype

Key advantage: separation of concernsKey advantage: separation of concerns Cross-cutting concerns: those that are not well Cross-cutting concerns: those that are not well

encapsulated in the usual OOD way – classesencapsulated in the usual OOD way – classes Often appear in the form of ‘code guidelines’Often appear in the form of ‘code guidelines’

For ExampleFor Example

public class SomeClass extends OtherClass {public class SomeClass extends OtherClass {    // Core data members    // Core data members    // Other data members: Log stream, consistency flag    // Other data members: Log stream, consistency flag

    public void DoSomething(OperationInformation info) {    public void DoSomething(OperationInformation info) {        // Ensure authentication        // Ensure authentication        // Ensure info satisfies contracts        // Ensure info satisfies contracts        // Lock the object in case other threads access it         // Lock the object in case other threads access it         // Ensure the cache is up to date        // Ensure the cache is up to date        // Log the start of operation        // Log the start of operation        //         // ==== Perform the core operation ======== Perform the core operation ====        // Log the completion of operation        // Log the completion of operation        // Unlock the object        // Unlock the object        // Do Standard Exception Handling        // Do Standard Exception Handling

          }}    // More operations similar to above    // More operations similar to above } }

Cross-Cutting ConcernsCross-Cutting Concerns

LoggingLogging DebuggingDebugging Profiling (Performance)Profiling (Performance) Security & AuthenticationSecurity & Authentication Exception HandlingException Handling Design by ContractDesign by Contract Event HandlingEvent Handling SynchronizationSynchronization Resource PoolingResource Pooling Others…Others…

Current SolutionsCurrent Solutions

Problems: Code Tangling, Code ScatteringProblems: Code Tangling, Code Scattering Reduced reuse, speed, quality, ability to changeReduced reuse, speed, quality, ability to change

Design patterns can solve some problemsDesign patterns can solve some problems Proxy, Template Method solve some casesProxy, Template Method solve some cases Visitor, Strategy solve other casesVisitor, Strategy solve other cases

Frameworks provide domain-specific solutionsFrameworks provide domain-specific solutions But it’s not a solution for cases in which:But it’s not a solution for cases in which:

Polymorphism can’t be used (exceptions, DbC)Polymorphism can’t be used (exceptions, DbC) Concerns are only used during debug, and change a lotConcerns are only used during debug, and change a lot The designer didn’t plan for a given concernThe designer didn’t plan for a given concern The framework wasn’t designed to consider a concernThe framework wasn’t designed to consider a concern

Separation of ConcernsSeparation of Concerns Separate logical concerns should be in separate Separate logical concerns should be in separate

modules of code – called aspectsmodules of code – called aspects

OOD & AOPOOD & AOP

Object-Oriented ProgrammingObject-Oriented Programming Basic concept of modularity : the classBasic concept of modularity : the class Good for common concerns (inheritance)Good for common concerns (inheritance) A program is a set of classesA program is a set of classes

Aspect-Oriented ProgrammingAspect-Oriented Programming Basic concept of modularity: the aspectBasic concept of modularity: the aspect Good for unrelated concerns (pointcuts)Good for unrelated concerns (pointcuts) A program is a set of aspectsA program is a set of aspects

AOP complements OODAOP complements OOD

AspectJAspectJ

AspectJ is the leading AOP implementation, AspectJ is the leading AOP implementation, and the only full, stable and widely used oneand the only full, stable and widely used one

It includes a language specificationIt includes a language specification A set of additions to the Java languageA set of additions to the Java language A compiler that creates standard Java bytecodeA compiler that creates standard Java bytecode

It includes a set of toolsIt includes a set of tools Aspect-aware debugger and documentation toolAspect-aware debugger and documentation tool Visual aspect browserVisual aspect browser Integration with popular IDEsIntegration with popular IDEs

Hello, WorldHello, World

Let’s start with a simple exampleLet’s start with a simple example // HelloWorld.java// HelloWorld.java

public class HelloWorld {public class HelloWorld {    public static void say(String message) {    public static void say(String message) {        System.out.println(message);        System.out.println(message);    }    }            public static void sayToPerson(    public static void sayToPerson( String message, String name) { String message, String name) {        System.out.println(name + ", " + message);        System.out.println(name + ", " + message);    }    }}}

Polite Hello, WorldPolite Hello, World Guess what the following aspect doesGuess what the following aspect does

// MannersAspect.java// MannersAspect.javapublic public aspectaspect MannersAspect { MannersAspect {        pointcutpointcut callSayMessage() : callSayMessage() : call(public static void HelloWorld.say*(..)); call(public static void HelloWorld.say*(..));

        before()before() : callSayMessage() { : callSayMessage() {        System.out.println("Good day!");        System.out.println("Good day!");    }    }

        after()after() : callSayMessage() { : callSayMessage() {        System.out.println("Thank you!");        System.out.println("Thank you!");    }    }}}

Running the ExampleRunning the Example

Just Compile and RunJust Compile and Run ajc HelloWorld.java MannersAspect.javaajc HelloWorld.java MannersAspect.java (or *.aj) (or *.aj) ajc –argfile PoliteHelloWorld.lstajc –argfile PoliteHelloWorld.lst

What’s in the exampleWhat’s in the example A A PointcutPointcut defines at which points in the dynamic defines at which points in the dynamic

execution of the program – at what execution of the program – at what Join Points Join Points – – extra code should be insertedextra code should be inserted

An An AdviceAdvice defines when, relative to the join point, defines when, relative to the join point, the new code runs, and that actual codethe new code runs, and that actual code

An An AspectAspect encapsulates pointcuts and advices encapsulates pointcuts and advices

Join PointsJoin Points

Well-defined points in a program’s executionWell-defined points in a program’s execution AspectJ makes these join points available: AspectJ makes these join points available:

Method call and execution Method call and execution Constructor call and execution Constructor call and execution Read/write access to a field Read/write access to a field Exception handler execution Exception handler execution Object and class initialization executionObject and class initialization execution

A join point may include other join pointsA join point may include other join points A join point may have a contextA join point may have a context

PointcutsPointcuts

Definition of a collection of join pointsDefinition of a collection of join points Call to or execute methods and constructors:Call to or execute methods and constructors:

call(public void MyClass.myMethod(String))call(public void MyClass.myMethod(String)) execute(void MyClass.myMethod(..)) execute(void MyClass.myMethod(..)) call(* MyClass.myMethod*(..)) call(* MyClass.myMethod*(..)) // * means wildcard// * means wildcard execute(* MyClass.myMethod*(String,..)) execute(* MyClass.myMethod*(String,..)) call(* *.myMethod(..)) call(* *.myMethod(..)) execute(MyClass.new(..)) execute(MyClass.new(..)) call(MyClass+.new(..)) call(MyClass+.new(..)) // + is subclass wildcard// + is subclass wildcard execute(public * com.mycompany..*.*(..)) execute(public * com.mycompany..*.*(..))

Pointcuts IIPointcuts II

Field access pointcutsField access pointcuts get(PrintStream System.out) get(PrintStream System.out) set(int MyClass.x) set(int MyClass.x)

Exception handling pointcuts Exception handling pointcuts ((catchcatch execution) execution) handler(RemoteException) handler(RemoteException) handler(IOException+) handler(IOException+) handler(CreditCard*)handler(CreditCard*)

Object and class initialization pointcutsObject and class initialization pointcuts Staticinitialization(MyClass+) Staticinitialization(MyClass+)

Pointcuts IIIPointcuts III

Inside lexical scope of class or methodInside lexical scope of class or method within(MyClass)within(MyClass) // of class// of class withincode(* MyClass.myMethod(..)) withincode(* MyClass.myMethod(..)) // of method// of method

Control-flow based pointcutsControl-flow based pointcuts If a() calls b(), then b() is inside a()’s control flowIf a() calls b(), then b() is inside a()’s control flow cflow(call(* MyClass.myMethod(..)) cflow(call(* MyClass.myMethod(..)) cflowbelow(call(* MyClass.myMethod(..))cflowbelow(call(* MyClass.myMethod(..))

Conditional test pointcutsConditional test pointcuts if(EventQueue.isDispatchThread())if(EventQueue.isDispatchThread())

Pointcuts IVPointcuts IV

Context-based pointcutsContext-based pointcuts this(JComponent+) this(JComponent+) // ‘this’ inherits from JComponent// ‘this’ inherits from JComponent

target(MyClass) target(MyClass) // match type of method call’s target// match type of method call’s target

args(String,..,int) args(String,..,int) // match order & type of arguments// match order & type of arguments

args(RemoteException) args(RemoteException) // type of argument or handler// type of argument or handler

You can use &&, || and ! operatorsYou can use &&, || and ! operators call(* MyClass.m1()) || call(* MyClass.m2())call(* MyClass.m1()) || call(* MyClass.m2())

You can expose context in pointcutsYou can expose context in pointcutspointcut publicCardAmount(CreditCard card, Money amount):pointcut publicCardAmount(CreditCard card, Money amount):

execution(public * CreditCardManager.*(..)) && args(card, amount); execution(public * CreditCardManager.*(..)) && args(card, amount);

Pointcuts can be named or anonymousPointcuts can be named or anonymous

AdviceAdvice

Defines the code to run, and when to run itDefines the code to run, and when to run it Based on pointcuts, for example Based on pointcuts, for example move()move()::

after(): move() {after(): move() {System.out.println("A figure element moved."); System.out.println("A figure element moved.");

}} Before and After adviceBefore and After advice

before() : call(public * MyClass.*(..)) {before() : call(public * MyClass.*(..)) {         System.out.println("Before: " +          System.out.println("Before: " + thisJoinPointthisJoinPoint + " " + + " " +

System.currentTimeMillis()); } System.currentTimeMillis()); }

after() : call(public * MyClass.*(..)) {after() : call(public * MyClass.*(..)) {         System.out.println("After: " +          System.out.println("After: " + thisJoinPointthisJoinPoint + " " + + " " + System.currentTimeMillis()); } System.currentTimeMillis()); }

Advice IIAdvice II

Around adviceAround advice Surrounds join point, can decide if computation Surrounds join point, can decide if computation

will happen, can modify argumentswill happen, can modify arguments

void void aroundaround(Connection conn) :(Connection conn) :call(Connection.close()) && target(conn) {call(Connection.close()) && target(conn) {    if (enablePooling) {    if (enablePooling) {        connectionPool.put(conn);        connectionPool.put(conn);    } else {    } else {                proceed()proceed();;    }    }}}

thisJoinPointthisJoinPoint

A useful reflection-like feature, can provide:A useful reflection-like feature, can provide: the kind of join point that was matched the kind of join point that was matched the source location of the current join point the source location of the current join point normal, short and long string representations of the normal, short and long string representations of the

current join point current join point actual argument(s) to the method / field of the join point actual argument(s) to the method / field of the join point signature of the method or field of the current join point signature of the method or field of the current join point the target object the target object the currently executing object the currently executing object a reference to the static portion of the object holding a reference to the static portion of the object holding

the join point; also available in the join point; also available in thisJoinPointStaticPartthisJoinPointStaticPart

AspectsAspects

Unit that combines pointcuts and advicesUnit that combines pointcuts and advices Can contain methods and fieldsCan contain methods and fields Can extend classes or implement interfacesCan extend classes or implement interfaces Cannot create an ‘aspect object’ using Cannot create an ‘aspect object’ using newnew Aspects and pointcuts can be abstractAspects and pointcuts can be abstract Classes can define pointcuts tooClasses can define pointcuts too

These must be declared staticThese must be declared static This is not recommended practiceThis is not recommended practice Advices can’t be declared inside classesAdvices can’t be declared inside classes

Abstract AspectsAbstract Aspects

A generic aspect requiring authentication A generic aspect requiring authentication through a singleton Authenticator:through a singleton Authenticator:

// AbstratcAuthenticationAspect.java// AbstratcAuthenticationAspect.javapublic public abstractabstract aspectaspect AbstractAuthenticationAspect { AbstractAuthenticationAspect {    public public abstractabstract pointcutpointcut opsNeeddingAuthentication(); opsNeeddingAuthentication();  before() : opsNeeddingAuthentication() {  before() : opsNeeddingAuthentication() {        // Perform authentication. If not authenticated,        // Perform authentication. If not authenticated,        // let the thrown exception propagate.        // let the thrown exception propagate.        Authenticator.authenticate();        Authenticator.authenticate();    }    }}}

Abstract Aspects IIAbstract Aspects II

A concrete aspect for a database app:A concrete aspect for a database app:

// DatabaseAuthenticationAspect.java// DatabaseAuthenticationAspect.javapublic public aspectaspect DatabaseAuthenticationAspect DatabaseAuthenticationAspect         extendsextends AbstractAuthenticationAspect { AbstractAuthenticationAspect {

    public     public pointcutpointcut opsNeeddingAuthentication(): opsNeeddingAuthentication():        call(* DatabaseServer.connect());        call(* DatabaseServer.connect());}}

More Aspect FeaturesMore Aspect Features

You can declare an aspect as dominant, in You can declare an aspect as dominant, in case several affect the same join pointcase several affect the same join point declaredeclare precedenceprecedence: : TypePatternListTypePatternList ; ;

Aspects don’t have to be singletonsAspects don’t have to be singletons Useful in case they contain fieldsUseful in case they contain fields There are other association typesThere are other association types perthisperthis, , pertargetpertarget, , percflowpercflow, , percflowbelowpercflowbelow

Aspects can be allowed to use private Aspects can be allowed to use private fields of aspected classesfields of aspected classes The The privilegedprivileged keyword keyword

IntroductionsIntroductions

Modifying the static form of a classModifying the static form of a class Add fields to an existing classAdd fields to an existing class

private boolean Server.disabled = false;private boolean Server.disabled = false; public String Foo.name;public String Foo.name;

Add methods to an existing classAdd methods to an existing class public int Point.getX() { return x; }public int Point.getX() { return x; } public String (Point || Line).getName() { return name; }public String (Point || Line).getName() { return name; }

Add ConstructorsAdd Constructors public Point.new(int x, int y) { this.x = x; this.y = y; }public Point.new(int x, int y) { this.x = x; this.y = y; }

Introductions IIIntroductions II

Extend an existing class with anotherExtend an existing class with another declaredeclare parentsparents: Point : Point extendsextends GeometricObject; GeometricObject;

Implement an interface with an existing classImplement an interface with an existing class declaredeclare parentsparents: Point : Point implementsimplements Comparable; Comparable;

““Soften” ExceptionSoften” Exception Convert checked exceptions to unchecked onesConvert checked exceptions to unchecked ones Wraps exceptions in Wraps exceptions in org.aspectj.lang.SoftExceptionorg.aspectj.lang.SoftException declaredeclare softsoft: CloneNotSupportedException:: CloneNotSupportedException:

execution(Object clone()); execution(Object clone());

Introductions IIIIntroductions III

Add a compile-time warning or errorAdd a compile-time warning or error Issued if there is a chance that code will Issued if there is a chance that code will

reach a given pointcutreach a given pointcut Warning / error string can be definedWarning / error string can be defined

declare warning: declare warning: PointcutPointcut: : StringString;; declare error: declare error: PointcutPointcut: : StringString; ;

ExamplesExamples

Development Time ExamplesDevelopment Time Examples Tracing / Logging: Printing “Debug Messages”Tracing / Logging: Printing “Debug Messages” Profiling with fine-grained controlProfiling with fine-grained control Contract enforcementContract enforcement Flexible method access controlFlexible method access control

Production Time ExamplesProduction Time Examples Realizing design patterns: ObserverRealizing design patterns: Observer Implementing Mixins: Making classes CloneableImplementing Mixins: Making classes Cloneable Modularizing functional guidelinesModularizing functional guidelines

TracingTracing

We’d like to print debug traces for each We’d like to print debug traces for each method entry or exit in all method entry or exit in all EntityEntity subclasses subclasses

Without aspects, we can define:Without aspects, we can define: public public classclass Trace { Trace {

public static int TRACELEVEL = 0; public static int TRACELEVEL = 0; public static void initStream(PrintStream s) {...} public static void initStream(PrintStream s) {...} public static void traceEntry(String str) {...} public static void traceEntry(String str) {...} public static void traceExit(String str) {...} } public static void traceExit(String str) {...} }

And manually call And manually call trace*()trace*() in all classes in all classes This is difficult to modify to remove laterThis is difficult to modify to remove later

Tracing: Solution 1Tracing: Solution 1 First solution using an aspect:First solution using an aspect:aspectaspect TraceEntities { TraceEntities {

pointcutpointcut myClass(): myClass(): within(Entity+); within(Entity+);pointcutpointcut myConstructor(): myConstructor(): myClass() && execution(new(..)); myClass() && execution(new(..));pointcutpointcut myMethod(): myMethod(): myClass() && execution(* *(..)); myClass() && execution(* *(..));beforebefore (): myConstructor() { (): myConstructor() { Trace.traceEntry(""+thisJoinPoint.getSignature()); } Trace.traceEntry(""+thisJoinPoint.getSignature()); }afterafter(): myConstructor() {(): myConstructor() { Trace.traceExit("" + thisJoinPoint.getSignature()); } Trace.traceExit("" + thisJoinPoint.getSignature()); } beforebefore (): myMethod() { (): myMethod() { Trace.traceEntry("" + thisJoinPoint.getSignature()); } Trace.traceEntry("" + thisJoinPoint.getSignature()); } afterafter(): myMethod() {(): myMethod() { Trace.traceExit("" + thisJoinPoint.getSignature()); } } Trace.traceExit("" + thisJoinPoint.getSignature()); } }

Tracing: Solution 2Tracing: Solution 2

Define an abstract, generic tracing aspect:Define an abstract, generic tracing aspect:abstractabstract aspectaspect Trace { Trace {

public static int TRACELEVEL = 2;public static int TRACELEVEL = 2;public static void initStream(PrintStream s) {...} public static void initStream(PrintStream s) {...} protected static void traceEntry(String str) {...} protected static void traceEntry(String str) {...} protected static void traceExit(String str) {...} protected static void traceExit(String str) {...} abstractabstract pointcutpointcut myClass(); } myClass(); }

Define a concrete implementation:Define a concrete implementation:public public aspectaspect TraceMyClasses extends Trace { TraceMyClasses extends Trace {

pointcutpointcut myClass(): within(Entity+); myClass(): within(Entity+);public static void main(String[] args) {public static void main(String[] args) { Trace.initStream(System.err); Trace.initStream(System.err); ExampleMain.main(args); } } ExampleMain.main(args); } }

ProfilingProfiling

It’s easy to ask very specific questions, and It’s easy to ask very specific questions, and quickly modify them, all outside the real codequickly modify them, all outside the real code

aspectaspect SetsInRotateCounting { SetsInRotateCounting {int rotateCount = 0;int rotateCount = 0;int setCount = 0;int setCount = 0;beforebefore(): (): callcall(void Line.rotate(double)) {(void Line.rotate(double)) { rotateCount++; } rotateCount++; }beforebefore():(): callcall(void Point.set*(int)) &&(void Point.set*(int)) && cflowcflow(call(void Line.rotate(double))) {(call(void Line.rotate(double))) { setCount++; } setCount++; } } }

Contract EnforcementContract Enforcement

Useful to check assertions, use Design by Useful to check assertions, use Design by Contract, or validate framework assumptionsContract, or validate framework assumptions

The following checks that only certain factory The following checks that only certain factory methods can put objects in a central Registrymethods can put objects in a central Registry

staticstatic aspectaspect RegistrationProtection { RegistrationProtection {pointcutpointcut register(): register(): callcall(void Registry.register(Element));(void Registry.register(Element));pointcutpointcut canRegister(): canRegister(): withincodewithincode(static * Element.make*(..));(static * Element.make*(..));beforebefore(): register() && !canRegister() {(): register() && !canRegister() { throw new IllegalAccessException("Illegal call " + throw new IllegalAccessException("Illegal call " + thisJoinPoint); } thisJoinPoint); }} }

Flexible Access ControlFlexible Access Control

Control method access beyond Control method access beyond privateprivate, , protectedprotected and and publicpublic declarations declarations

Violations must be found at compile timeViolations must be found at compile time For example, class Product can only be For example, class Product can only be

initialized and configured by specific classesinitialized and configured by specific classes

public public classclass Product { Product {    public Product() {    public Product() {        /* constructor implementation */  }        /* constructor implementation */  }    public void configure() {    public void configure() {        /* configuration implementation */   }        /* configuration implementation */   }

Flexible Access Control IIFlexible Access Control II

Use Use declare errordeclare error inside a nested aspect inside a nested aspectstatic static aspectaspect FlagAccessViolation { FlagAccessViolation {

pointcutpointcut factoryAccessViolation() factoryAccessViolation()     :     : callcall(Product.new(..)) && !(Product.new(..)) && !withinwithin(ProductFactory+);(ProductFactory+);pointcutpointcut configuratorAccessViolation() configuratorAccessViolation()     :     : callcall(* Product.configure(..)) &&(* Product.configure(..)) && ! !withinwithin(ProductConfigurator+);(ProductConfigurator+);declaredeclare errorerror             :  factoryAccessViolation() ||            :  factoryAccessViolation() || configuratorAccessViolation() configuratorAccessViolation()             : "Access control violation";            : "Access control violation";    } // end of aspect     } // end of aspect } // end of class} // end of class

Subject & ObserverSubject & Observer

The following aspect is an ‘automatic’ The following aspect is an ‘automatic’ observer for Screen objects observing Pointsobserver for Screen objects observing Points

aspectaspect PointObserving { PointObserving { private Vector Point.observers = new Vector(); private Vector Point.observers = new Vector();

public static void addObserver(Point p, Screen s) {public static void addObserver(Point p, Screen s) { p.observers.add(s); } p.observers.add(s); }

public static void removeObserver(Point p, Screen s) {public static void removeObserver(Point p, Screen s) { p.observers.remove(s); } p.observers.remove(s); }

static void updateObserver(Point p, Screen s) {static void updateObserver(Point p, Screen s) {

s.display(p); } s.display(p); }

Subject & Observer IISubject & Observer II

pointcutpointcut changes(Point p): changes(Point p): targettarget(p) && (p) && callcall(void Point.set*(int)); (void Point.set*(int));

afterafter(Point p): changes(p) { (Point p): changes(p) { Iterator iter = p.observers.iterator();Iterator iter = p.observers.iterator();while ( iter.hasNext() ) {while ( iter.hasNext() ) { updateObserver(p, (Screen)iter.next()); } updateObserver(p, (Screen)iter.next()); }}}

This can be easily generalizedThis can be easily generalized Same pattern is useful for logging, profiling, …Same pattern is useful for logging, profiling, … Aspects are by default singletons, so their Aspects are by default singletons, so their

fields and methods are by default staticfields and methods are by default static

Making a Class CloneableMaking a Class Cloneable

Given a standard Given a standard PointPoint class, with private class, with private fields fields x,yx,y we can make it cloneable: we can make it cloneable:

aspectaspect CloneablePoint { CloneablePoint { declaredeclare parentsparents: Point : Point implementsimplements Cloneable; Cloneable; declaredeclare softsoft: CloneNotSupportedException:: CloneNotSupportedException: executionexecution(Object clone());(Object clone()); Object Point.clone() { return super.clone(); } Object Point.clone() { return super.clone(); }} }

The same technique can be used for any The same technique can be used for any mixin that has a standard implementationmixin that has a standard implementation

Functional GuidelinesFunctional Guidelines

““Every time a slow operation is used, the Every time a slow operation is used, the cursor should turn into a wait cursor”cursor should turn into a wait cursor”

public public abstractabstract aspectaspect SlowMethodAspect { SlowMethodAspect {        abstractabstract pointcutpointcut slowMethods(Component uiComp); slowMethods(Component uiComp);    void     void aroundaround(Component uiComp) :(Component uiComp) : slowMethods(uiComp) { slowMethods(uiComp) {         Cursor originalCursor = uiComp.getCursor();         Cursor originalCursor = uiComp.getCursor();         Cursor waitCursor = Cursor.WAIT_CURSOR;         Cursor waitCursor = Cursor.WAIT_CURSOR;         uiComp.setCursor(waitCursor);         uiComp.setCursor(waitCursor);         try {         try {                          proceedproceed(uiComp);(uiComp);         } finally {         } finally {             uiComp.setCursor(originalCursor);             uiComp.setCursor(originalCursor);         }   } }          }   } }

Functional GuidelinesFunctional Guidelines

Code of aspected classes doesn’t changeCode of aspected classes doesn’t change Multiple aspects can co-existMultiple aspects can co-exist Same pattern is useful for many other casesSame pattern is useful for many other cases

Security, AuthenticationSecurity, Authentication Resource Pooling, Caching, Copy on write, …Resource Pooling, Caching, Copy on write, … Creation by Factory, Lazy Creation, …Creation by Factory, Lazy Creation, … Multi-Thread SynchronizationMulti-Thread Synchronization Transaction DefinitionTransaction Definition Monitoring System NotificationMonitoring System Notification Standard Exception HandlingStandard Exception Handling

SummarySummary

AOP is a strong complement to OODAOP is a strong complement to OOD Separation of concerns for unrelated aspectsSeparation of concerns for unrelated aspects Less code, more modular, easier to modifyLess code, more modular, easier to modify A lot of practical usesA lot of practical uses A lot of hypeA lot of hype

AspectJ is the primary implementation todayAspectJ is the primary implementation today Many features, good tools and active supportMany features, good tools and active support Yet the entire platform is still in ‘beta version’Yet the entire platform is still in ‘beta version’

A good tool, during development for nowA good tool, during development for now