1 Aspect-Oriented Programming Dimple Kaul ACCRE Vanderbilt University Nashville, Tennessee dkaul
-
Upload
sara-stokes -
Category
Documents
-
view
219 -
download
0
Transcript of 1 Aspect-Oriented Programming Dimple Kaul ACCRE Vanderbilt University Nashville, Tennessee dkaul
1
Aspect-Oriented ProgrammingAspect-Oriented Programming
Dimple KaulACCRE
Vanderbilt University Nashville, Tennessee
http://www.dre.vanderbilt.edu/~dkaul/
2
Talk Outline
Problem Scenario Aspect Oriented Programming Aspect & Object Oriented Programming Aspect Terminology Examples Installation of AJDT First Steps Conclusion Questions
3
Problem Scenario (1/2)
class Foo { public void foo () { bar.doSomething (); }}
class Bar { static void doSomething () { baz.doSomething (); }}
class Baz { static void doSomething () { for (int i = 0; i < 100; i++) { doSomething(i); } }}
Regular OO Java Adding new logging functionality
class Foo { public void foo () { logger.log ("Start -- Foo.foo()"); bar.doSomething (); logger.log ("End -- Foo.foo()"); }}
class Bar { static void doSomething () { logger.log ("Start -- Bar.doSomething()"); baz.doSomething (); logger.log ("End -- Bar.doSomething()"); }}
class Baz { static void doSomething () { logger.log ("Start -- Baz.doSomething()"); for (int i = 0; i < 100; i++) { doSomething(i); } logger.log ("End -- Baz.doSomething()"); }}.
Logging code is inserted at many places in the code
4
Problem Scenario (2/2)
Rewriting former logging example in Aspect Oriented Programming way. Original code will not change….
aspect Logging {
pointcut log () : execution (void *.*()) || execution (static void Baz.doSomething()) ; before(): log() { Logger.log("Start --" + thisJoinPoint.getSignature ()); }
after(): log() { Logger.log( “End --" + thisJoinPoint.getSignature ()); }}
This procedure is executed when methods written as "execution(X)" are executed.
"thisJoinPoint" object has an information about the method called.
5
Problem
Software systems consists of several concerns
For example: In a credit card processing
Primary Concern (System core)
processing of payment
Secondary Concern (System level)
authentication, security & logging etc
Object Oriented Programming provide good modularity for primary concerns i.e., the main business logic
Adding secondary concerns (crosscutting concerns) with primary concern result into a system which is difficult to understand and evolve and result into code tangling & scattering
6
Aspect Oriented Programming (1/2)
AOP shows great promise in specialization : Functionality can often be changed without re-factoring code
No need for knowing “ahead of time” functionality If a system does not have logging or exception handling
functionality
These concerns can be added anytime without even touching original code
Components can be integrated incrementally
Implementations are easier to design, understand, & maintain
7
Aspect Oriented Programming(2/2)
Supports the reuse of existing code by applying new features in a controlled and localized way
AOP promises higher productivity, improved quality, & better ability to implement newer features
AOP has been implemented in different languages (for example, C++, Smalltalk, C#, C, and Java)
AOP builds on top of other programming paradigms: object-oriented, procedural or functional
8
What is AOP?
Aspect-oriented programming (AOP) methodology facilitates modularization of crosscutting concerns
Separation of concerns
breaking down of a program into distinct parts that overlap in functionality as little as possible
“Untangle your code into cross-cutting, loosely coupled aspect”
9
Aspect
Requirement
AspectAspect
Requirement Requirement
(b) Aspect Oriented Model
Class Class Class Class
Requirement Requirement Requirement
(a) Object Oriented Model
Requirement is dependent on multiple classes
“[...] In programs P, whenever condition C arises, perform action A”
Each requirement can have separate aspect
AOP & OOP
10
AOP & OOP Terminology
Object Oriented Aspect OrientedClass – code unit that encapsulates methods & attributes.
Aspect – code unit that encapsulates pointcuts, advice, & attributes.
Method signatures – define the entry points for the execution of method bodies.
Pointcut – define the set of entry points (triggers) in which advice is executed.
Method bodies – implementations of the primary concerns.
Advice – implementations of the cross cutting concerns.
Compiler – converts source code into object code.
Weaver – instruments code (source or object) with advice.
Aspect Oriented Programming languages include AspectJ, AspectC++, & JBOSS AOP
11
Aspect-Oriented Development
Softwarerequirements
AOP
OOP
Aspects
ClassesInterfaces Executable
software
Concerns
Concern identifier
WEAVER
Existing OOP Project
AOP
OOP
Aspects
ClassesInterfaces
Executablesoftware
ConcernsWEAVER
New functionality
Concern identifier
Concerns
12
Aspect Oriented Programming
Implications of tangling & scattering on software design Maintainability: Nightmare for huge systems
Poor traceability: simultaneous coding of many concerns in a module breaks linkage between the requirement & its implementation
Lower productivity: developer is paying too much attention to peripheral issues rather than the business logic
Less code reuse: cut-&-paste code between modules is the lowest form of reuse and is more error prone
Harder re-factoring: changing requirements means touching many modules for a single concern
13
Dynamic VS Static crosscutting
Dynamic crosscutting define additional behavior to run at certain
well-defined points in the execution of the program
Static crosscutting modify the static structure of a program (e.g.,
adding new methods, implementing new interfaces, modifying the class hierarchy)
14
AOP TerminologyJoinPoints & Pointcut
JoinPoints:Well-defined points in the execution of a program: Method call / execution Constructor call / execution Object initialization
Pointcuts: A set of join point, plus, optionally, some of the values in
the execution context of those join points. Can be composed using Boolean operators || , && Matched at runtime
For more detail see AspectJ Quick Reference Manual
15
AOP Terminology JoinPoints & Pointcut contd… Example:
pointcut set() : execution( * *.set*(..) ) && this(Point) Captures all executions of any method that begins with set in
an object of type Point
pointcut abc() : call ( public void MyClass.myMethod(..) ) Captures call of myMethod method of MyClass class with any
number of arguments
within ( org.package.* ) Captures all join point where the associated code is defined in
the package “org.package.*”
withincode ( void Figure.move() ) Capture all join points where the associated code is defined in
the method void Figure.move()
“*” is wild card“..” is multi-part wild card
16
AOP TerminologyAdvice
It executes when a pointcut matches before(): runs just prior to the join point
before(): log() { Logger.log("Start --" + thisJoinPoint.getSignature ()); }
after(): runs just after the join pointafter(): log() { Logger.log(("End --" + thisJoinPoint.getSignature ()); }
17
AOP TerminologyAdvice contd…
after() returning – runs after the method returns normallyafter() returning(int x) : call(int getX()) {
System.out.println("Returning int value " + x + " for p = " + p);
}
after() throwing – runs after the method throws an exception abruptlyafter() throwing (SQLException ex) : inDataLayer() {
logException(ex);
}
18
AOP TerminologyAdvice contd…
around(): runs before &/or after, with the operation taking place via a call to proceed(). Note, if proceed is not called, then the advised code is skipped.
pointcut log () : execution (void *.*()) || execution (static void Baz.doSomething()) ;
around(): log() { Logger.log("Start --" + thisJoinPoint.getSignature ()); proceed(); Logger.log( “ End --" + thisJoinPoint.getSignature ());}
19
AOP TerminologyOthers… Inter-type declaration: Allows to add method, fields or interfaces to existing
classes from within aspectsaspect VisitAspect {
Point.acceptVisitor(Visitor v) { v.visit(this);
} }aspect DeclareErrorWarning { declare error : get(java.io.PrintStream System.out) &&
within(figures..*) : "illegal access to System.out";}
Aspect: container holding point cuts & advice
Weaver: the tool that instruments the primary concerns with the advice based on matched pointcuts.
Method added
Declared error
20
Example showing Advice, Pointcut and Aspectaspect Logging {
pointcut log () : execution (void *.*()) || execution (static void Baz.doSomething()) ; before(): log() { Logger.log("Start --" + thisJoinPoint.getSignature ()); }
after(): log() { Logger.log(“End --" + thisJoinPoint.getSignature ()); }
Pointcut
Piece of AdviceAspect
21
Weaving Types
Advice is inserted at Compile-time: source code is instrumented
before compilation. (AspectC++) Link-time: object code (byte code) is
instrumented after compilation (AspectJ) Load-time: specialized class loaders
instrument code (AspectWerkz) Run-time: virtual machine instruments or
application framework intercepts loaded code (JBossAOP, XWork).
22
AspectJ & AOP
AspectJ is an aspect-oriented extension to the Java programming language
It was originally developed and co-founded by Gregor Kiczales and his team at Xerox PARC
Later Xerox group’s work was integrated with Eclipse Java IDE
Freely available implementation Compiler, tools and plugins are Open source
23
Example (Simple bank account class)
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.}
24
Example (Adding pre-condition checking)
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"); }}
25
Example Exception HandlingCatch any exception in all the public methods: aspect CatchException{ // Catch any exception in all the public methods void around(): execution(public * *(..)){ try{ proceed(); } catch(Exception e){ System.out.println("Printing exception"); //Handle exception } }}
Catch SQL exceptions that need to be logged:after() throwing (SQLException ex) : inDataLayer() { logException(ex);}
Throwing of exception:aspect ThrowException { private boolean Point.inGroup = false; before(Point p): execution(void Group.add(FigureElement)) &&
args(p) { if (p.inGroup) { throw new IllegalStateException(); } else { p.inGroup = true; } }}
26
Example of Persistence
aspect DatabaseAspect {
pointcut transactionalMethods (): execution (/* pattern for transactional
methods */) ; before(): transactionalMethods () { initialiseDatabase() ; } after() returning: transactionalMethods() { commitTransaction() ; } after() throwing: transactionalMethods() { rollbackTransaction() ; }}
27
Uses Cases for AOP
Not only for Logging & Exception Handling Thread Safety Multi-Object Protocol Performance optimization
Middleware Specialization using AOP (http://www.dre.vanderbilt.edu/~dkaul/pdf/acm_aspect.pdf)
Timing / Monitoring /Tracing Various kinds of invasive/non-invasive instrumentation Authentication & Authorization Transactional management /Locking Session Handling Synchronization Caching
28
Why bother with AOP?
Capture the crosscutting concern explicitly Both the behavior of the concern The specification of its applicability
Change is easier Change the aspect – no grepping
Aspects can be plugged in or out easily Many people suggest use of patterns, template
and careful programming as alternative to AOP Research has proved that all these proposed ideas
always fail to localize the crosscutting concerns. Then tend to have some code that remains in base structure
29
Installing AspectJ
Download AJDT plugin for eclipse from: http://download.eclipse.org/technology/ajdt/30/update
AspectJ Development Tools (AJDT) project provides Eclipse platform based tool support for AOSD with AspectJ
Runtime library required for AspectJ is a very small library of about 35K
It creates normal java class files & can be execute on any JVM
Aspect files can have .Java or .aj extension Weaves into class files Produces standard Java bytecode
30
First StepsConverting existing Java project
It enables us to use AspectJ language to implement the applications , & AspectJ compiler to build it
Converting regular existing Java project to AspectJ will be like this…
31
Step 1:
Select Project from the package explorer & Right click & choose “Convert to AspectJ Project” from the context menu
32
Step 2:
Some changes in the Package Explorer are seen
First, the project icon has changed from the Java project icon J to AspectJ project icon AJ
Second, a new jar file has been added to the project's build path, using the Eclipse path variable ASPECTJRT_LIB
Creates build configuration file which stores information about the build of project
33
First Steps (contd..)Creating new AspectJ projects
To do this, you use the New AspectJ Project Wizard. You can reach the wizard via the Eclipse workbench menus by selecting File -> New -> Project, & then AspectJ Project.
34
35
36
First Steps (contd..)Configuring Workbench
First time you convert old java project to Aspectj or create new Aspectj project we need to configure workbench
Preference window will come up to set some settings
You can also change these preferences at any stage by going through eclipse workbench menus by selecting Window -> Preference -> AspectJ
37
Create New Aspect
To creating new aspect for a package
Select package in the package explorer & right click to go to context menu & do New ->Aspect
38
Skeletal Aspect
39
Moving back to regular Java project
Easy to revert back to your regular java project
40
Select Project from the package explorer & Right click & choose “Remove AspectJ Nature” from the context menu
It is a good idea not use Aspectj related artifacts in actual project otherwise we may get build errors Good practice to keep
aspect file extension as .aj
41
History of AOP
AOP has been following other technologies like OOP
Worked in academia Popping up more & more in real world
42
Conclusion
AOP is an evolutionary step Not a replacement of OOP, but is used to enhance it Decomposes the system into primary & crosscutting
concerns which map more directly into requirements. Easy to understand system by reducing tangling &
scattering. Joinpoints, pointcuts, & advice are used to instrument
primary concerns with crosscutting concerns If you’ve got an orthogonal concern that is about exactly
one place in the original code, & you’re sure that that orthogonal concern will not propagate to other loci as the system evolves, it is probably a bad idea to use AOP
43
Related Work
Traditional techniques: Code re-factoring Ahead-of-time design
Modern techniques: Feature-Oriented Programming
Incremental stepwise refinement Feature modularity features are basic design
components
Hybrid Programming (FeatureC++) Mix of AOP & FOP Still research is going on
But have shortcomings:
• Manual & Error prone• High Memory consumption• Performance overhead
44
Questions??
45
References
AspectJ.org. (2004). AspectJ Sample Code. Retrieved May 11, 2004, from the AspectJ documentation: http://dev.eclipse.org/viewcvs/indextech.cgi/~checkout~/aspectj-home/sample-code.html
C2.com. (2004). You Arent Gonna Need It. Retrieved May 11, 2004, from the Extreme Programming Wiki: http://xp.c2.com/YouArentGonnaNeedIt.html.
Gradecki, J., & Lesiecki, N. (2003). Mastering AspectJ: Aspect-Oriented Programming in Java. Indianapolis, IN: Wiley Publishing.
Laddad, R. (2002). I want my AOP! Part 1. Retrieved May 11, 2004, from JavaWorld: http://www.javaworld.com/javaworld/jw-01-2002/jw-0118-aspect_p.html
Laddad, R. (2002). I want my AOP! Part 2. Retrieved May 11, 2004, from JavaWorld: http://www.javaworld.com/javaworld/jw-03-2002/jw-0301-aspect2_p.html
Laddad, R. (2003). AspectJ in Action: Practical Aspect-Oriented Programming. Greenwich, CT: Manning Publications.
46
Defining Pointcuts
Calling methods & constructors Advice is inserted after argument evaluation, but before
calling. Access to caller’s context
Pointcut Description
call (public void MyClass.myMethod(String))
Call to myMethod() in MyClass taking a String argument, returning void, & 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
“*” is wild card“..” is multi-part wild card
47
Defining Pointcuts
Control flow based pointcuts
Pointcut Description
cflow (call (* MyClass.myMethod(..))
All the join points in control flow of call to any myMethod() in MyClass including call to the specified method itself
cflowbelow (call (* MyClass.myMethod(..))
All the join points in control flow of call to any myMethod() in MyClass excluding call to the specified method itself
48
Defining Pointcuts
Context capturing pointcuts Can attach names to the types to capture the variables for use
inside the associated advice.
Pointcut Description
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 & the last argument is of int type
args (RemoteException)All the join points where the type of argument or exception handler type is RemoteException
49
Defining Pointcuts
Execution of methods & constructors Advice is inserted in the method or constructor body itself.
Access to callee’s context. Replace call with execution. Field access – read or write
Pointcut Description
get (int MyClass.x)Execution of read-access to field x of type int in MyClass
set (int MyClass.x)Execution of write-access to field x of type int in MyClass
50
Defining Pointcuts
Pointcuts & logical operators Can be combined with &&, ||, & !
before(): execution(public * *(..)) && within(figures.*) { Log.write(thisJoinPoint);}
51
What is AOP?
The AOP-style solution Three phase implementation (Laddad, 2003)
Aspectual decomposition: based on requirements, extract concerns, identifying them as primary & crosscutting.
Concern implementation: code each concern separately – primary (OO), crosscutting (AO).
Aspectual re-composition: tools weave the separately implemented code together into a final instrumented software system.