+ All Categories
Home > Documents > Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect...

Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect...

Date post: 15-Jul-2018
Category:
Upload: phamkhue
View: 218 times
Download: 4 times
Share this document with a friend
13
Aspect Oriented Aspect Oriented Aspect Oriented Aspect Oriented Programming Programming Todd A. Whittaker Todd A. Whittaker Franklin University Franklin University Franklin University Franklin University [email protected] [email protected] What is AOP? What is AOP? Addresses Addresses crosscutting crosscutting concerns concerns Requirements analysis leads to identification Requirements analysis leads to identification Requirements analysis leads to identification Requirements analysis leads to identification of of concerns concerns in a software system. in a software system. Primary concerns are issues within the problem Primary concerns are issues within the problem domain. i.e. domain. i.e. InvoiceProcessor InvoiceProcessor, , Item Item, , Shipper Shipper, , ReorderProcessor ReorderProcessor, etc. classes that are central to , etc. classes that are central to solving the problems of inventory control. solving the problems of inventory control. Crosscutting concerns are the important (even Crosscutting concerns are the important (even Crosscutting concerns are the important (even Crosscutting concerns are the important (even critical) issues that cross typical OO class critical) issues that cross typical OO class boundaries. i.e. logging, transaction control, boundaries. i.e. logging, transaction control, authorization and authentication authorization and authentication
Transcript
Page 1: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

Aspect Oriented Aspect Oriented Aspect Oriented Aspect Oriented ProgrammingProgramming

Todd A. WhittakerTodd A. WhittakerFranklin UniversityFranklin UniversityFranklin UniversityFranklin University

[email protected]@franklin.edu

What is AOP?What is AOP?

�� Addresses Addresses crosscuttingcrosscutting concernsconcernsRequirements analysis leads to identification Requirements analysis leads to identification �� Requirements analysis leads to identification Requirements analysis leads to identification of of concernsconcerns in a software system.in a software system.

•• Primary concerns are issues within the problem Primary concerns are issues within the problem domain. i.e. domain. i.e. InvoiceProcessorInvoiceProcessor, , ItemItem, , ShipperShipper, , ReorderProcessorReorderProcessor, etc. classes that are central to , etc. classes that are central to solving the problems of inventory control.solving the problems of inventory control.

•• Crosscutting concerns are the important (even Crosscutting concerns are the important (even •• Crosscutting concerns are the important (even Crosscutting concerns are the important (even critical) issues that cross typical OO class critical) issues that cross typical OO class boundaries. i.e. logging, transaction control, boundaries. i.e. logging, transaction control, authorization and authenticationauthorization and authentication

Page 2: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

What is AOP?What is AOP?

Concern

BusinessLogic

ConcernIdentifier

RequirementsSecurity

Logging

(Laddad, 2003, p. 9)

What is AOP?What is AOP?

�� NonNon--AOP AOP implementation of implementation of

Security

implementation of implementation of crosscutting concerns crosscutting concerns leads to leads to code tanglingcode tanglingand and code scatteringcode scattering..

•• TanglingTangling: concerns are : concerns are interwoven with each interwoven with each other in a module.other in a module.

•• ScatteringScattering: concerns : concerns are dispersed over are dispersed over

BusinessLogic

Logging

ShoppingCart

Inventory

are dispersed over are dispersed over many modules.many modules.

•• Typical design problem Typical design problem of highof high--coupling and coupling and low cohesion.low cohesion. Billing Shipping

Check forauthorization

(Laddad, 2003, p. 16, 17)

Page 3: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

What is AOP?What is AOP?

�� Implications of tangling and scattering on Implications of tangling and scattering on software design (Laddad, 2002)software design (Laddad, 2002)software design (Laddad, 2002)software design (Laddad, 2002)

•• Poor traceabilityPoor traceability: simultaneous coding of many : simultaneous coding of many concerns in a module breaks linkage between the concerns in a module breaks linkage between the requirement and its implementation.requirement and its implementation.

•• Lower productivityLower productivity: developer is paying too much : developer is paying too much attention to peripheral issues rather than the attention to peripheral issues rather than the business logic.business logic.

•• Less code reuseLess code reuse: cut: cut--andand--paste code between paste code between modules is the lowest form of reuse.modules is the lowest form of reuse.

•• Harder refactoringHarder refactoring: changing requirements means : changing requirements means touching many modules for a single concern.touching many modules for a single concern.

What is AOP?What is AOP?

�� The AOPThe AOP--style solutionstyle solutionThree phase implementation (Laddad, 2003)Three phase implementation (Laddad, 2003)�� Three phase implementation (Laddad, 2003)Three phase implementation (Laddad, 2003)

•• Aspectual decompositionAspectual decomposition: based on requirements, : based on requirements, extract concerns, identifying them as primary and extract concerns, identifying them as primary and crosscutting.crosscutting.

•• Concern implementationConcern implementation: code each concern : code each concern separatelyseparately –– primary (OO), crosscutting (AO).primary (OO), crosscutting (AO).separatelyseparately –– primary (OO), crosscutting (AO).primary (OO), crosscutting (AO).

•• Aspectual recompositionAspectual recomposition: tools : tools weaveweave the the separately implemented code together into a final separately implemented code together into a final instrumented software system.instrumented software system.

Page 4: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

What is AOP?What is AOP?

ConcernIdentifier

Requirements

Weaver

Concernimplementation

Final SystemRequirements

AspectualDecomposition

AspectualRecomposition

Final System

(Laddad, 2003, p. 22)

What is AOP?What is AOP?

�� Complementary to OOP as OOP was to Complementary to OOP as OOP was to procedural programmingprocedural programmingprocedural programmingprocedural programming

•• Not a replacement for OOP, rather a superset of Not a replacement for OOP, rather a superset of OO. i.e. every valid Java program is also a valid OO. i.e. every valid Java program is also a valid AspectJ program.AspectJ program.

�� Complementary to the XP process as wellComplementary to the XP process as well•• YAGNI “You Aren’t Gonna Need It”: Always YAGNI “You Aren’t Gonna Need It”: Always •• YAGNI “You Aren’t Gonna Need It”: Always YAGNI “You Aren’t Gonna Need It”: Always

implement things when you implement things when you actuallyactually need them, need them, never when you just never when you just foreseeforesee that you need them that you need them (C2.com, 2004).(C2.com, 2004).

Page 5: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

AOP TerminologyAOP Terminology

�� Common terms in AOP (Gradecki, 2003)Common terms in AOP (Gradecki, 2003)join pointjoin point: a well: a well--defined location within the defined location within the �� join pointjoin point: a well: a well--defined location within the defined location within the primary code where a concern can crosscut.primary code where a concern can crosscut.

•• Method calls, method execution, constructor calls, Method calls, method execution, constructor calls, constructor execution, field access (read or write), constructor execution, field access (read or write), exception handler execution, etc.exception handler execution, etc.

�� PointcutPointcut: a set of join points.: a set of join points.�� PointcutPointcut: a set of join points.: a set of join points.•• Can be named or anonymousCan be named or anonymous•• When a pointcut is matched, advice can be When a pointcut is matched, advice can be

executed.executed.

AOP TerminologyAOP Terminology

�� AdviceAdvice: code to be executed when a pointcut : code to be executed when a pointcut is matched.is matched.is matched.is matched.

•• Can be executed Can be executed beforebefore, , aroundaround, or , or afterafter a a particular join point.particular join point.

•• Analogous to eventAnalogous to event--driven database triggers.driven database triggers.

�� AspectAspect: container holding point cuts & advice: container holding point cuts & advice•• Analogous to a class holding methods and Analogous to a class holding methods and

attributes.attributes.attributes.attributes.

�� WeaverWeaver: the tool that instruments the primary : the tool that instruments the primary concerns with the advice based on matched concerns with the advice based on matched pointcuts.pointcuts.

Page 6: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

AOP TerminologyAOP Terminology

Object OrientedObject Oriented Aspect OrientedAspect OrientedClass Class –– code unit that code unit that Aspect Aspect –– code unit that code unit that Class Class –– code unit that code unit that encapsulates methods and encapsulates methods and attributes.attributes.

Aspect Aspect –– code unit that code unit that encapsulates pointcuts, advice, encapsulates pointcuts, advice, and attributes.and attributes.

Method signatures Method signatures –– define the define the entry points for the execution of entry points for the execution of method bodies.method bodies.

Pointcut Pointcut –– define the set of entry define the set of entry points (triggers) in which advice is points (triggers) in which advice is executed.executed.

Method bodies Method bodies –– implementations implementations of the primary concerns.of the primary concerns.

Advice Advice –– implementations of the implementations of the cross cutting concerns.cross cutting concerns.of the primary concerns.of the primary concerns. cross cutting concerns.cross cutting concerns.

Compiler Compiler –– converts source code converts source code into object code.into object code.

Weaver Weaver –– instruments code instruments code (source or object) with advice.(source or object) with advice.

Weaving TypesWeaving Types

�� When can advice be inserted?When can advice be inserted?CompileCompile--timetime: source code is instrumented : source code is instrumented �� CompileCompile--timetime: source code is instrumented : source code is instrumented before compilation. (AspectC++)before compilation. (AspectC++)

�� LinkLink--timetime: object code (byte code) is : object code (byte code) is instrumented after compilation (AspectJ)instrumented after compilation (AspectJ)

�� LoadLoad--timetime: specialized class loaders : specialized class loaders instrument code (AspectWerkz)instrument code (AspectWerkz)instrument code (AspectWerkz)instrument code (AspectWerkz)

�� RunRun--timetime: virtual machine instruments or : virtual machine instruments or application framework intercepts loaded code application framework intercepts loaded code (JBossAOP, XWork).(JBossAOP, XWork).

Page 7: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

Defining PointcutsDefining Pointcuts

�� Calling methods & constructors (Laddad, 2002)Calling methods & constructors (Laddad, 2002)Advice is inserted after argument evaluation, but Advice is inserted after argument evaluation, but �� Advice is inserted after argument evaluation, but Advice is inserted after argument evaluation, but before calling. Access to caller’s context.before calling. Access to caller’s context.

PointcutPointcut DescriptionDescription

call (public void

MyClass.myMethod(String))Call to myMethod() in MyClass taking a Stringargument, returning void, and public access

call (* MyClass.myMethod*(..))Call to any method with name starting in "myMethod" in MyClass

call (MyClass.new(..))Call to any MyClass' constructor with any

call (MyClass.new(..))Call to any MyClass' constructor with any arguments

call (MyClass+.new(..))Call to any MyClass or its subclass's constructor. (Subclass indicated by use of '+' wildcard)

call (public * com.mycompany..*.*(..))

All public methods in all classes in any package with com.mycompany the root package

Defining PointcutsDefining Pointcuts

�� Execution of methods & constructorsExecution of methods & constructorsAdvice is inserted in the method or constructor body Advice is inserted in the method or constructor body �� Advice is inserted in the method or constructor body Advice is inserted in the method or constructor body itself. Access to itself. Access to callee’scallee’s context. Replace context. Replace callcall with with executionexecution..

�� Field access Field access –– read or writeread or writePointcutPointcut DescriptionDescription

Execution of read-access to field out of type get (PrintStream System.out)

Execution of read-access to field out of type PrintStream in System class

set (int MyClass.x) Execution of write-access to field x of type int in MyClass

(Laddad, 2002)

Page 8: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

Defining PointcutsDefining Pointcuts

�� Lexically based Lexically based pointcutspointcuts�� Keyword Keyword withinwithin captures all join points in a class, and captures all join points in a class, and �� Keyword Keyword withinwithin captures all join points in a class, and captures all join points in a class, and

withincodewithincode captures all join points in a particular captures all join points in a particular method.method.

�� Control flow based Control flow based pointcutspointcuts

PointcutPointcut DescriptionDescription

cflowcflow ((callcall (* (* MyClass.myMethodMyClass.myMethod(..)) (..))

All the join points in control flow of call to any myMethod() in MyClass including call to the specified

MyClass.myMethodMyClass.myMethod(..)) (..)) myMethod() in MyClass including call to the specified method itself

cflowbelowcflowbelow ((callcall (* (* MyClass.myMethodMyClass.myMethod(..))(..))

All the join points in control flow of call to any myMethod() in MyClass excluding call to the specified method itself

(Laddad, 2002)

Defining PointcutsDefining Pointcuts

�� Context capturing pointcutsContext capturing pointcutsCan attach names to the types to capture the Can attach names to the types to capture the �� Can attach names to the types to capture the Can attach names to the types to capture the variables for use inside the associated advice.variables for use inside the associated advice.

PointcutPointcut DescriptionDescription

this (JComponent+) All the join points where this is instanceof JComponent

target (MyClass)All the join points where the object on which the method is called is of type MyClass

All the join points where the first argument is of Stringargs (String,..,int)

All the join points where the first argument is of Stringtype and the last argument is of int type

args (RemoteException)All the join points where the type of argument or exception handler type is RemoteException

(Laddad, 2002)

Page 9: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

Defining PointcutsDefining Pointcuts

�� PointcutsPointcuts and logical operatorsand logical operatorsCan be combined with Can be combined with , , , and , and �� Can be combined with Can be combined with &&&&, , ||||, and , and !!

•• Ex: Capture Ex: Capture publicpublic operations on operations on CreditCardProcessorCreditCardProcessor which take arguments of which take arguments of CreditCardCreditCard and and MoneyMoney. (. (LaddadLaddad, 2002), 2002)

pointcut cardProc(CreditCard card, Money amount):execution (public * CreditCardProcessor.*(..))execution (public * CreditCardProcessor.*(..))&& args (card, amount);

AdvicesAdvices

�� Advice executes when a Advice executes when a pointcutpointcut matches.matches.Three instrumentation pointsThree instrumentation points�� Three instrumentation pointsThree instrumentation points•• beforebefore: executes just prior to the join point.: executes just prior to the join point.•• afterafter: executes just after the join point.: executes just after the join point.•• aroundaround: executes before and/or after, with the : executes before and/or after, with the

operation taking place via a call to operation taking place via a call to proceed()proceed()..

Page 10: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

ExampleExample

Simple bank account classSimple bank account classpackage org.thewhittakers.banking;package org.thewhittakers.banking;public class Account implements Loggable {

private double balance;private String owner;

public Account(String owner, double initialBalance) {this.setOwner(owner);this.credit(initialBalance);

}

public void credit(double amount) {this.balance += amount;

}}

public void debit(double amount) {this.balance -= amount;

}

public void transferTo(Account other, double amount) {this.debit(amount);other.credit(amount);

} // less interesting items removed.}

ExampleExample

Adding preAdding pre--condition checkingcondition checkingpackage org.thewhittakers.banking;package org.thewhittakers.banking;

public aspect AccountConstraintsAspect {pointcut preventNegativeAmounts(Account account, double amount)

: (execution(* Account.credit(double))|| execution(* Account.debit(double)))&& this(account) && args(amount);

pointcut preventOverdraft(Account account, double amount): execution(* Account.debit(double))

&& this(account) && args(amount);

before(Account account, double amount):preventNegativeAmounts(account, amount) {if (amount < 0)

throw new RuntimeException("Negative amounts not permitted");}

before(Account account, double amount): preventOverdraft(account, amount) {if (account.getBalance() < amount)

throw new RuntimeException("Insufficient funds");}

}

Page 11: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

ExampleExample

Adding indented logging (Laddad, 2003, p. 171)Adding indented logging (Laddad, 2003, p. 171)package org.thewhittakers.banking;package org.thewhittakers.banking;

public abstract aspect IndentedLoggingAspect {protected int indentationLevel = 0;protected abstract pointcut loggedOperations();

before() : loggedOperations() {++this.indentationLevel;

}

after() : loggedOperations() {--this.indentationLevel;

}}

before() : call(* java.io.PrintStream.println(..))&& within(IndentedLoggingAspect+) {for (int i=0, spaces = this.indentationLevel<<2; i<spaces; ++i){

System.out.print(" ");}

}}

ExampleExample

OptOpt--in logging (AspectJ.org, 2004)in logging (AspectJ.org, 2004)package org.thewhittakers.banking;

import org.aspectj.lang.*;

public aspect OptInIndentedLoggingAspect extends IndentedLoggingAspect{

protected pointcut loggedOperations(): this(Loggable)

&& (execution(* Loggable+.*(..))|| execution(Loggable+.new(..)));

before() : loggedOperations() {Signature sig = thisJoinPointStaticPart.getSignature();Signature sig = thisJoinPointStaticPart.getSignature();System.out.println("Entering [“

+ sig.getDeclaringType().getName()+ "." + sig.getName() + "]");

}}

Page 12: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

ConclusionConclusion

�� AOP is an evolutionary stepAOP is an evolutionary stepDoes not supplant OOP, but enhances it.Does not supplant OOP, but enhances it.�� Does not supplant OOP, but enhances it.Does not supplant OOP, but enhances it.

•• Decomposes the system into primary and Decomposes the system into primary and crosscutting concerns which map more directly into crosscutting concerns which map more directly into requirements.requirements.

•• Increases comprehension of the system by Increases comprehension of the system by reducing tangling and scattering.reducing tangling and scattering.reducing tangling and scattering.reducing tangling and scattering.

•• Joinpoints, pointcuts, and advice are used to Joinpoints, pointcuts, and advice are used to instrument primary concerns with crosscutting instrument primary concerns with crosscutting concerns.concerns.

QuestionsQuestions

�� Questions? Comments? Experiences?Questions? Comments? Experiences?

Page 13: Aspect Oriented Programming - Franklin Universitycs.franklin.edu/~whittakt/AOP04.pdf · Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu What

ReferencesReferencesAspectJ.org. (2004). AspectJ.org. (2004). AspectJ Sample CodeAspectJ Sample Code. Retrieved May 11, 2004, from the . Retrieved May 11, 2004, from the

AspectJ documentation: AspectJ documentation: http://dev.eclipse.org/viewcvs/indextech.cgi/~checkout~/aspectj-home/sample-code.htmlhttp://dev.eclipse.org/viewcvs/indextech.cgi/~checkout~/aspectj-home/sample-code.html

C2.com. (2004). C2.com. (2004). You Arent Gonna Need ItYou Arent Gonna Need It. Retrieved May 11, 2004, from the . Retrieved May 11, 2004, from the Extreme Programming Wiki: Extreme Programming Wiki: http://xp.c2.com/YouArentGonnaNeedIt.htmlhttp://xp.c2.com/YouArentGonnaNeedIt.html..

Gradecki, J., & Lesiecki, N. (2003). Gradecki, J., & Lesiecki, N. (2003). Mastering AspectJ: AspectMastering AspectJ: Aspect--Oriented Oriented Programming in JavaProgramming in Java. Indianapolis, IN: Wiley Publishing.. Indianapolis, IN: Wiley Publishing.

Laddad, R. (2002). Laddad, R. (2002). I want my AOP! Part 1I want my AOP! Part 1. Retrieved May 11, 2004, from . Retrieved May 11, 2004, from JavaWorld: JavaWorld: http://www.javaworld.com/javaworld/jwhttp://www.javaworld.com/javaworld/jw--0101--2002/jw2002/jw--01180118--aspect_p.htmlaspect_p.html

Laddad, R. (2002). Laddad, R. (2002). I want my AOP! Part 2I want my AOP! Part 2. Retrieved May 11, 2004, from . Retrieved May 11, 2004, from JavaWorld: JavaWorld: http://www.javaworld.com/javaworld/jwhttp://www.javaworld.com/javaworld/jw--0303--2002/jw2002/jw--03010301--JavaWorld: JavaWorld: http://www.javaworld.com/javaworld/jwhttp://www.javaworld.com/javaworld/jw--0303--2002/jw2002/jw--03010301--aspect2_p.htmlaspect2_p.html

Laddad, R. (2003). Laddad, R. (2003). AspectJ in Action: Practical AspectAspectJ in Action: Practical Aspect--Oriented ProgrammingOriented Programming. . Greenwich, CT: Manning Publications.Greenwich, CT: Manning Publications.


Recommended