AspectOriented Programming Dimple Kaul ACCRE Vanderbilt University Nashville
Aspect-Oriented Programming Dimple Kaul ACCRE Vanderbilt University Nashville, Tennessee http: //www. dre. vanderbilt. edu/~dkaul/ 1
Talk Outline n n n n n Problem Scenario Aspect Oriented Programming Aspect & Object Oriented Programming Aspect Terminology Examples Installation of AJDT First Steps Conclusion Questions 2
Problem Scenario (1/2) Regular OO Java class Foo { public void foo () { bar. do. Something (); } } class Bar { static void do. Something () { baz. do. Something (); } } class Baz { static void do. Something () { for (int i = 0; i < 100; i++) { do. Something(i); } } } Logging code is inserted at many places in the code Adding new logging functionality class Foo { public void foo () { logger. log ("Start -- Foo. foo()"); bar. do. Something (); logger. log ("End -- Foo. foo()"); } } class Bar { static void do. Something () { logger. log ("Start -- Bar. do. Something()"); baz. do. Something (); logger. log ("End -- Bar. do. Something()"); } } class Baz { static void do. Something () { logger. log ("Start -- Baz. do. Something()"); for (int i = 0; i < 100; i++) { do. Something(i); } logger. log ("End -- Baz. do. Something()"); } } 3.
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. do. Something()) ; before(): log() { Logger. log("Start } after(): log() { Logger. log( “End } } --" + this. Join. Point. get. Signature ()); This procedure is executed when methods written as "execution(X)" are executed. --" + this. Join. Point. get. Signature ()); "this. Join. Point" object has an information about the method called. 4
Problem n Software systems consists of several concerns For example: In a credit card processing ¨ Primary Concern (System core) n ¨ processing of payment Secondary Concern (System level) n authentication, security & logging etc n Object Oriented Programming provide good modularity for primary concerns i. e. , the main business logic n Adding secondary concerns (crosscutting concerns) with primary concern result into a system which is difficult to understand evolve and result into code tangling & scattering 5
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 n n 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 6
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 7
What is AOP? n Aspect-oriented programming (AOP) methodology facilitates modularization of crosscutting concerns n 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” 8
AOP & OOP Requirement Class Requirement is dependent on multiple classes Requirement Class (a) Object Oriented Model Requirement Aspect (b) Aspect Oriented Model Each requirement can have separate aspect “[. . . ] In programs P, whenever condition C arises, perform action 9 A”
AOP & OOP Terminology Object Oriented Aspect Oriented Class – 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 Aspect. J, Aspect. C++, & JBOSS AOP 10
Aspect-Oriented Development Concerns Concern Software requirements identifier OOP AOP Classes Interfaces Aspects Executable software WEAVER Existing OOP Project OOP Classes Interfaces Concerns New Concerns functionality Concern identifier AOP Executable software Aspects WEAVER 11
Aspect Oriented Programming ¨ Implications of tangling & scattering on software design n n 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 12
Dynamic VS Static crosscutting n Dynamic crosscutting ¨ n 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) 13
AOP Terminology Join. Points & Pointcut n Join. Points: Well-defined points in the execution of a program: ¨ Method call / execution ¨ Constructor call / execution ¨ Object initialization n 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 Aspect. J Quick Reference Manual 14
AOP Terminology Join. Points & Pointcut contd… n Example: ¨ pointcut set() : execution( * *. set*(. . ) ) && this(Point) n ¨ pointcut abc() : call ( public void My. Class. my. Method(. . ) ) n ¨ Captures call of my. Method method of My. Class class with any number of arguments within ( org. package. * ) n ¨ Captures all executions of any method that begins with set in an object of type Point Captures all join point where the associated code is defined in the package “org. package. *” withincode ( void Figure. move() ) n Capture all join points where the associated code is defined in the method void Figure. move() “*” is wild card “. . ” is multi-part wild card 15
AOP Terminology Advice n It executes when a pointcut matches ¨ before(): runs just prior to the join point before(): log() { Logger. log("Start } ¨ --" + this. Join. Point. get. Signature ()); after(): runs just after the join point after(): log() { Logger. log(("End } --" + this. Join. Point. get. Signature ()); 16
AOP Terminology Advice contd… ¨ after() returning – runs after the method returns normally after() returning(int x) : call(int get. X()) { System. out. println("Returning int value " + x + " for p = " + p); } ¨ after() throwing – runs after the method throws an exception abruptly after() throwing (SQLException ex) : in. Data. Layer() { log. Exception(ex); } 17
AOP Terminology Advice 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. do. Something()) ; around(): log() { Logger. log("Start --" + this. Join. Point. get. Signature ()); proceed(); Logger. log( “ End --" + this. Join. Point. get. Signature ()); } 18
AOP Terminology Others… n Inter-type declaration: Allows to add method, fields or interfaces to existing classes from within aspects aspect Visit. Aspect { Point. accept. Visitor(Visitor v) { Method added v. visit(this); } } Declared error aspect Declare. Error. Warning { declare error : get(java. io. Print. Stream System. out) && within(figures. . *) : "illegal access to System. out"; } n Aspect: container holding point cuts & advice n Weaver: the tool that instruments the primary concerns with the advice based on matched pointcuts. 19
Example showing Advice, Pointcut and Aspect aspect Logging { Pointcut pointcut log () : execution (void *. *()) || execution (static void Baz. do. Something()) ; before(): log() { Logger. log("Start --" + this. Join. Point. get. Signature ()); } after(): log() { Logger. log(“End --" + this. Join. Point. get. Signature ()); } Aspect Piece of Advice 20
Weaving Types n Advice is inserted at n n Compile-time: source code is instrumented before compilation. (Aspect. C++) Link-time: object code (byte code) is instrumented after compilation (Aspect. J) Load-time: specialized class loaders instrument code (Aspect. Werkz) Run-time: virtual machine instruments or application framework intercepts loaded code (JBoss. AOP, XWork). 21
Aspect. J & AOP n n Aspect. J 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 22
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 initial. Balance) { this. set. Owner(owner); this. credit(initial. Balance); } public void credit(double amount) { this. balance += amount; } public void debit(double amount) { this. balance -= amount; } public void transfer. To(Account other, double amount) { this. debit(amount); other. credit(amount); } // less interesting items removed. } 23
Example (Adding pre-condition checking) package org. thewhittakers. banking; public aspect Account. Constraints. Aspect { pointcut prevent. Negative. Amounts(Account account, double amount) : (execution(* Account. credit(double)) || execution(* Account. debit(double))) && this(account) && args(amount); pointcut prevent. Overdraft(Account account, double amount) : execution(* Account. debit(double)) && this(account) && args(amount); before(Account account, double amount): prevent. Negative. Amounts(account, amount) { if (amount < 0) throw new Runtime. Exception("Negative amounts not permitted"); } before(Account account, double amount): prevent. Overdraft(account, amount) { if (account. get. Balance() < amount) throw new Runtime. Exception("Insufficient funds"); } } 24
Example Exception Handling Catch any exception in all the public methods: aspect Catch. Exception{ // Catch any exception in all the public methods void around(): execution(public * *(. . )){ try{ proceed(); } catch(Exception e){ System. out. println("Printing exception"); //Handle exception } } } Throwing of exception: aspect Throw. Exception { private boolean Point. in. Group = false; before(Point p): execution(void Group. add(Figure. Element)) && args(p) { if (p. in. Group) { throw new Illegal. State. Exception(); } else { p. in. Group = true; } } } Catch SQL exceptions that need to be logged: after() throwing (SQLException ex) : in. Data. Layer() { log. Exception(ex); } 25
Example of Persistence aspect Database. Aspect { pointcut transactional. Methods (): execution (/* pattern for transactional methods */) ; before(): transactional. Methods () { initialise. Database() ; } after() returning: transactional. Methods() { commit. Transaction() ; } after() throwing: transactional. Methods() { rollback. Transaction() ; } } 26
Uses Cases for AOP Not only for Logging & Exception Handling n n n Thread Safety Multi-Object Protocol Performance optimization ¨ n n n n 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 27
Why bother with AOP? n Capture the crosscutting concern explicitly n n n Change is easier n n n Both the behavior of the concern The specification of its applicability 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 n 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 28
Installing Aspect. J n Download AJDT plugin for eclipse from: http: //download. eclipse. org/technology/ajdt/30/update n n n Aspect. J Development Tools (AJDT) project provides Eclipse platform based tool support for AOSD with Aspect. J Runtime library required for Aspect. J is a very small library of about 35 K 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 29
First Steps Converting existing Java project n It enables us to use Aspect. J language to implement the applications , & Aspect. J compiler to build it n Converting regular existing Java project to Aspect. J will be like this… 30
Step 1: Select Project from the package explorer & Right click & choose “Convert to Aspect. J Project” from the context menu 31
Step 2: § Some changes in the Package Explorer are seen § First, the project icon has changed from the Java project icon J to Aspect. J 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 32
First Steps (contd. . ) Creating new Aspect. J projects n To do this, you use the New Aspect. J Project Wizard. You can reach the wizard via the Eclipse workbench menus by selecting File -> New -> Project, & then Aspect. J Project. 33
34
35
First Steps (contd. . ) Configuring Workbench n n n 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 -> Aspect. J 36
Create New Aspect n n To creating new aspect for a package Select package in the package explorer & right click to go to context menu & do New ->Aspect 37
Skeletal Aspect 38
Moving back to regular Java project n Easy to revert back to your regular java project 39
n n Select Project from the package explorer & Right click & choose “Remove Aspect. J 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 40
History of AOP n n n AOP has been following other technologies like OOP Worked in academia Popping up more & more in real world 41
Conclusion n 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 orthogonal concern will not propagate to other loci as the system evolves, it is probably a bad idea to use AOP 42
Related Work Traditional techniques: § Code re-factoring § Ahead-of-time design Modern techniques: But have shortcomings: • Manual & Error prone • High Memory consumption • Performance overhead § Feature-Oriented Programming § Incremental stepwise refinement § Feature modularity features are basic design components § Hybrid Programming (Feature. C++) § Mix of AOP & FOP § Still research is going on 43
Questions? ? 44
References Aspect. J. org. (2004). Aspect. J Sample Code. Retrieved May 11, 2004, from the Aspect. J documentation: http: //dev. eclipse. org/viewcvs/indextech. cgi/~checkout~/aspectjhome/sample-code. html C 2. com. (2004). You Arent Gonna Need It. Retrieved May 11, 2004, from the Extreme Programming Wiki: http: //xp. c 2. com/You. Arent. Gonna. Need. It. html. Gradecki, J. , & Lesiecki, N. (2003). Mastering Aspect. J: Aspect-Oriented Programming in Java. Indianapolis, IN: Wiley Publishing. Laddad, R. (2002). I want my AOP! Part 1. Retrieved May 11, 2004, from Java. World: 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 Java. World: http: //www. javaworld. com/javaworld/jw-03 -2002/jw-0301 aspect 2_p. html Laddad, R. (2003). Aspect. J in Action: Practical Aspect-Oriented Programming. Greenwich, CT: Manning Publications. 45
Defining Pointcuts n n “*” is wild card “. . ” is multi-part wild card Calling methods & constructors Advice is inserted after argument evaluation, but before calling. Access to caller’s context Pointcut Description call (public void My. Class. my. Method(String)) Call to my. Method() in My. Class taking a String argument, returning void, & public access call (* My. Class. my. Method*(. . )) Call to any method with name starting in "my. Method" in My. Class call (My. Class. new(. . )) Call to any My. Class' constructor with any arguments call (My. Class+. new(. . )) Call to any My. Class 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 46
Defining Pointcuts n Control flow based pointcuts Pointcut Description cflow (call (* My. Class. my. Method(. . )) All the join points in control flow of call to any my. Method() in My. Class including call to the specified method itself cflowbelow (call (* My. Class. my. Method(. . )) All the join points in control flow of call to any my. Method() in My. Class excluding call to the specified method itself 47
Defining Pointcuts n 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 (My. Class) All the join points where the object on which the method is called is of type My. Class args (String, . . , int) All the join points where the first argument is of String type & the last argument is of int type args (Remote. Exception) All the join points where the type of argument or exception handler type is Remote. Exception 48
Defining Pointcuts n Execution of methods & constructors ¨ n 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 My. Class. x) Execution of read-access to field x of type int in My. Class set (int My. Class. x) Execution of write-access to field x of type int in My. Class 49
Defining Pointcuts n Pointcuts & logical operators ¨ Can be combined with &&, ||, & ! before() : execution(public * *(. . )) && within(figures. *) { Log. write(this. Join. Point); } 50
What is AOP? n The AOP-style solution ¨ Three n n n 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. 51
- Slides: 51