27
Aspect Oriented Aspect Oriented Programming Programming Todd A. Whittaker Todd A. Whittaker Franklin University Franklin University [email protected] [email protected]

Aspect Oriented Programming

Embed Size (px)

DESCRIPTION

Aspect Oriented Programming. Todd A. Whittaker Franklin University [email protected]. What is AOP?. Addresses crosscutting concerns Requirements analysis leads to identification of concerns in a software system. - PowerPoint PPT Presentation

Citation preview

Page 1: Aspect Oriented Programming

Aspect Oriented Aspect Oriented ProgrammingProgramming

Todd A. WhittakerTodd A. Whittaker

Franklin UniversityFranklin University

[email protected]@franklin.edu

Page 2: Aspect Oriented Programming

What is AOP?What is AOP?

Addresses Addresses crosscuttingcrosscutting concerns concerns Requirements analysis leads to identification Requirements analysis leads to identification

of of concernsconcerns in a software system. in a software system.• Primary concernsPrimary concerns are issues within the problem 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 concernsCrosscutting concerns are the important (even 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 3: Aspect Oriented Programming

What is AOP?What is AOP?

ConcernIdentifier

Requirements

BusinessLogic

SecurityLogging

(Laddad, 2003, p. 9)

Page 4: Aspect Oriented Programming

What is AOP?What is AOP? Non-AOP Non-AOP

implementation of implementation of crosscutting concerns crosscutting concerns leads to leads to code tanglingcode tangling and 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 many modules.many modules.

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

Security

BusinessLogic

Logging

ShoppingCart

Inventory

Billing Shipping

Check forauthorization

(Laddad, 2003, p. 16, 17)

Page 5: Aspect Oriented Programming

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)• 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-and-paste code between : cut-and-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.

Page 6: Aspect Oriented Programming

What is AOP?What is AOP?

The AOP-style solutionThe AOP-style solution 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).

• 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 7: Aspect Oriented Programming

What is AOP?What is AOP?

ConcernIdentifier

Requirements

W eaver

Concernimplementation

AspectualDecomposition

AspectualRecomposition

Final System

(Laddad, 2003, p. 22)

Page 8: Aspect Oriented Programming

What is AOP?What is AOP?

Complementary to OOP as OOP was to Complementary to OOP as OOP was to procedural 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

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 9: Aspect Oriented Programming

AOP TerminologyAOP Terminology

Common terms in AOP (Gradecki, 2003)Common terms in AOP (Gradecki, 2003) JoinpointJoinpoint: a well-defined location within the : a well-defined location within the

code (primary or crosscutting) where a code (primary or crosscutting) where a concern can crosscut.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.• 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.

Page 10: Aspect Oriented Programming

AOP TerminologyAOP Terminology

AdviceAdvice: code to be executed when a pointcut : code to be executed when a pointcut 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 event-driven database triggers.Analogous to event-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. 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 11: Aspect Oriented Programming

AOP TerminologyAOP Terminology

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

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

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

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

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

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

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

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

Page 12: Aspect Oriented Programming

Weaving TypesWeaving Types

When can advice be inserted?When can advice be inserted? Compile-timeCompile-time: source code is instrumented : source code is instrumented

before compilation. (AspectC++)before compilation. (AspectC++) Link-timeLink-time: object code (byte code) is : object code (byte code) is

instrumented after compilation (AspectJ)instrumented after compilation (AspectJ) Load-timeLoad-time: specialized class loaders : specialized class loaders

instrument code (AspectWerkz)instrument code (AspectWerkz) Run-timeRun-time: virtual machine instruments or : virtual machine instruments or

application framework intercepts loaded code application framework intercepts loaded code (JBossAOP, XWork).(JBossAOP, XWork).

Page 13: Aspect Oriented Programming

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

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 String argument, 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 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

Page 14: Aspect Oriented Programming

Defining PointcutsDefining Pointcuts

Execution of methods & constructorsExecution of methods & constructors Advice is inserted in the method or constructor body Advice is inserted in the method or constructor body

itself. Access to callee’s context. Replace itself. Access to callee’s context. Replace callcall with with executionexecution..

Field access – read or writeField access – read or writePointcutPointcut DescriptionDescription

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 15: Aspect Oriented Programming

Defining PointcutsDefining Pointcuts

Lexically based pointcutsLexically based pointcuts 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 pointcutsControl flow based pointcuts

PointcutPointcut DescriptionDescription

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

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

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

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

(Laddad, 2002)

Page 16: Aspect Oriented Programming

Defining PointcutsDefining Pointcuts

Context capturing pointcutsContext capturing pointcuts 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

args (String,..,int)All the join points where the first argument is of String type 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 17: Aspect Oriented Programming

Defining PointcutsDefining Pointcuts

Pointcuts and logical operatorsPointcuts and logical operators 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. (Laddad, 2002). (Laddad, 2002)

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

Page 18: Aspect Oriented Programming

AdvicesAdvices

Advice executes when a pointcut matches.Advice executes when a pointcut matches. 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(). . Note, if proceed is not called, then the advised Note, if proceed is not called, then the advised code is code is skippedskipped..

Page 19: Aspect Oriented Programming

ExampleExample

Simple bank account classSimple bank account classpackage 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.}

Page 20: Aspect Oriented Programming

ExampleExample

Adding pre-condition checkingAdding pre-condition checkingpackage 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 21: Aspect Oriented Programming

ExampleExample

Adding indented logging (Laddad, 2003, p. 171)Adding indented logging (Laddad, 2003, p. 171)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(" "); } }}

Page 22: Aspect Oriented Programming

ExampleExample

Opt-in logging (AspectJ.org, 2004)Opt-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(); System.out.println("Entering [“ + sig.getDeclaringType().getName() + "." + sig.getName() + "]"); }}

Page 23: Aspect Oriented Programming

TestsTestspublic class TestAccount extends TestCase implements Loggable{ private Account account;

// .. Snipped code .. protected void setUp() throws Exception { super.setUp(); account = new Account("Todd", initialBalance); }

public void testGoodCredit() { double amount = 20.0; account.credit(amount); assertEquals(account.getBalance(), initialBalance+amount, tolerance); }

public void testBadCredit() { try { account.credit(-20); fail("Should not accept negative amounts"); } catch (Exception e) { printError(e); } assertEquals(account.getBalance(), initialBalance, tolerance); }

Page 24: Aspect Oriented Programming

OutputOutput

Entering [org.thewhittakers.banking.TestAccount.setUp] Entering [org.thewhittakers.banking.Loggable.<init>] Entering [org.thewhittakers.banking.Account.<init>] Entering [org.thewhittakers.banking.Account.setOwner] Entering [org.thewhittakers.banking.Account.credit]Entering [org.thewhittakers.banking.TestAccount.testGoodCredit] Entering [org.thewhittakers.banking.Account.credit] Entering [org.thewhittakers.banking.Account.getBalance]Entering [org.thewhittakers.banking.TestAccount.tearDown]

Entering [org.thewhittakers.banking.TestAccount.setUp] Entering [org.thewhittakers.banking.Loggable.<init>] Entering [org.thewhittakers.banking.Account.<init>] Entering [org.thewhittakers.banking.Account.setOwner] Entering [org.thewhittakers.banking.Account.credit]Entering [org.thewhittakers.banking.TestAccount.testBadCredit] Entering [org.thewhittakers.banking.Account.credit] Entering [org.thewhittakers.banking.TestAccount.printError]*** Negative amounts not permitted *** Entering [org.thewhittakers.banking.Account.getBalance]Entering [org.thewhittakers.banking.TestAccount.tearDown]

Page 25: Aspect Oriented Programming

ConclusionConclusion

AOP is an evolutionary stepAOP is an evolutionary step 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.

• 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.

Page 26: Aspect Oriented Programming

QuestionsQuestions

Download presentation and examples:Download presentation and examples:http://www.thewhittakers.org/~todd/AOP.ziphttp://www.thewhittakers.org/~todd/AOP.zip

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

Page 27: Aspect Oriented Programming

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.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: Aspect-Oriented Mastering AspectJ: Aspect-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/jw-01-2002/jw-0118-aspect_p.htmlhttp://www.javaworld.com/javaworld/jw-01-2002/jw-0118-aspect_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/jw-03-2002/jw-0301-aspect2_p.htmlhttp://www.javaworld.com/javaworld/jw-03-2002/jw-0301-aspect2_p.html

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