Aspect Oriented Programming

Slides:



Advertisements
Similar presentations
AspectWerkz 2 - and the road to AspectJ 5 Jonas Bonér Senior Software Engineer BEA Systems.
Advertisements

Aspect Oriented Programming. AOP Contents 1 Overview 2 Terminology 3 The Problem 4 The Solution 4 Join point models 5 Implementation 6 Terminology Review.
©Ian Sommerville 2006Software Engineering, 8th edition. Chapter 32 Slide 1 Aspect-oriented Software Development.
Aspect Oriented Programming - AspectJ Radhika Rajput.
1 Aspect-Oriented Programming Dimple Kaul ACCRE Vanderbilt University Nashville, Tennessee
Overview of AspectJ Aspect Oriented Software Development Seminar Technion presented by Oren Mishali.
Aspect-Oriented Programming In Eclipse ® Aspect-Oriented Programming in Eclipse with AspectJ Dr Helen Hawkins and Sian January.
ASPECT ORIENTED SOFTWARE DEVELOPMENT Prepared By: Ebru Doğan.
University of British Columbia Software Practices Lab CAS Seminar 06 Fluid AJ - A Simple Fluid AOP Tool Terry Hon Gregor Kiczales.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Introduction to AOP.
Introduction to Aspect Oriented Programming Presented By: Kotaiah Choudary. Ravipati M.Tech IInd Year. School of Info. Tech.
Java Language and SW Dev’t
Aspect Oriented Programming (AOP) in.NET Brent Krueger 12/20/13.
Aspect Oriented Programming Razieh Asadi University of Science & Technology Mazandran Babol Aspect Component Based Software Engineering (ACBSE)
Session 2: AspectJ Mark Stobbe September 13,
Aspect Oriented Programming Scott Nykl CSSE 411 Senior Seminar.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
©Ian Sommerville 2006Software Engineering, 8th edition. Chapter 32 Slide 1 Aspect-oriented Software Development 1.
Aspect Oriented Programming Sumathie Sundaresan CS590 :: Summer 2007 June 30, 2007.
Aspect Oriented Programming Gülşah KARADUMAN.
Joel Phinney March 31, ◦ Concerns  Separation of Concerns, Tangled and Scattered Concerns, Cross-Cutting Concerns, Aspects ◦ Aspect-Oriented Software.
AOP-1 Aspect Oriented Programming. AOP-2 Aspects of AOP and Related Tools Limitation of OO Separation of Concerns Aspect Oriented programming AspectJ.
1 Proving aspect-oriented programming laws Leonardo Cole Paulo Borba Alexandre Mota Informatics Center Federal University of.
Virtual Support for Dynamic Join Points C. Bockisch, M. Haupt, M. Mezini, K. Ostermann Presented by Itai Sharon
Features of AOP languages AOP languages have the following main elements: –a join point model (JPM) wrt base PL –a specification language for expressing.
Inter-Type Declarations in AspectJ Awais Rashid Steffen Zschaler © Awais Rashid, Steffen Zschaler 2009.
AspectJ – AOP for Java Tom Janofsky. Instructor at Penn State Abington Consultant with Chariot Solutions JUG Member.
Chapter 8: Aspect Oriented Programming Omar Meqdadi SE 3860 Lecture 8 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Aspect Oriented Development Alex Beatty.  Purpose  Cross-cutting Concerns  Join Points, Pointcuts, and Advices  Weaving  Invasive vs. Non-Invasive.
Extending the Field Access Pointcuts of AspectJ to Arrays ICS 2006 – Taipei, December 2006 Kung Chen and Chin-Hung Chien* National Chengchi University.
1 Deriving Refactorings for AspectJ Leonardo Cole Paulo Borba Informatics Center Federal University of Pernambuco Brazil.
Aspect Oriented Programming Adlux Consultancy Services Pvt Ltd
问题 Code scattering Blocks of duplicated code Blocks of complementary code, and different modules implementing complementary parts of the concern Code.
Comparison of Different AOP Approaches Presented by: Xiaojing Wang.
AOSD'04, Lancaster, UK 1 Remote Pointcut - A Language Construct for Distributed AOP Muga Nishizawa (Tokyo Tech) Shigeru Chiba (Tokyo Tech) Michiaki Tatsubori.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Introduction to Yan Cui Aspect Oriented Programming by
CSC450 Software Engineering Devon M. Simmonds University of North Carolina, Wilmington 1.
AOP with AspectJ Awais Rashid, Steffen Zschaler © Awais Rashid, Steffen Zschaler 2009.
Aspect-Oriented Software Development (AOSD)
L’origine dei mali: le dipendenze tra componenti Stefano Leli 14° Workshop DotNetMarche Venerdì 16 aprile
 Is a programming paradigm  Extends OOP  Enables modularization of cross cutting concerns.
Features of AOP languages AOP languages have the following main elements: –a join point model (JPM) wrt base PL –a specification language for expressing.
Leveraging ColdSpring to build a robust Flex applications Chris Scott, Cynergy Systems.
Aspect-Oriented Programming
Java Primer 1: Types, Classes and Operators
Chengyu Sun California State University, Los Angeles
Aspect-Oriented Generation of the API Documentation for AspectJ
Exceptions, Interfaces & Generics
Aspect-Oriented Programming with the Eclipse AspectJ plug-in
University of Central Florida COP 3330 Object Oriented Programming
Creating and Using Classes
Aspect-Oriented Programming
Aspect-Oriented Programming
Aspect-Oriented Design and Patterns
AspectJ Syntax Basics.
Java Programming Language
Chengyu Sun California State University, Los Angeles
Chapter 1: Computer Systems
Units with – James tedder
Units with – James tedder
JAsCo an Aspect-Oriented approach tailored for
Focus of the Course Object-Oriented Software Development
CS520 Web Programming Spring – Aspect Oriented Programming
AspectAda Aspect-Oriented Programming for Ada95
Aspect Oriented Software Design
Aspect Oriented Programming
Refactoring the Aspectizable Interfaces: An Empirical Assessment
Presentation transcript:

Aspect Oriented Programming Todd A. Whittaker Franklin University whittakt@franklin.edu

What is AOP? Addresses crosscutting concerns Requirements analysis leads to identification of concerns in a software system. Primary concerns are issues within the problem domain. i.e. InvoiceProcessor, Item, Shipper, ReorderProcessor, etc. classes that are central to solving the problems of inventory control. Crosscutting concerns are the important (even critical) issues that cross typical OO class boundaries. i.e. logging, transaction control, authorization and authentication

What is AOP? (Laddad, 2003, p. 9)

What is AOP? Non-AOP implementation of crosscutting concerns leads to code tangling and code scattering. Tangling: concerns are interwoven with each other in a module. Scattering: concerns are dispersed over many modules. Typical design problem of high-coupling and low cohesion. (Laddad, 2003, p. 16, 17)

What is AOP? Implications of tangling and scattering on software design (Laddad, 2002) Poor traceability: simultaneous coding of many concerns in a module breaks linkage between the requirement and its implementation. Lower productivity: developer is paying too much attention to peripheral issues rather than the business logic. Less code reuse: cut-and-paste code between modules is the lowest form of reuse. Harder refactoring: changing requirements means touching many modules for a single concern.

What is AOP? The AOP-style solution Three phase implementation (Laddad, 2003) Aspectual decomposition: based on requirements, extract concerns, identifying them as primary and crosscutting. Concern implementation: code each concern separately – primary (OO), crosscutting (AO). Aspectual recomposition: tools weave the separately implemented code together into a final instrumented software system.

What is AOP? (Laddad, 2003, p. 22)

What is AOP? Complementary to OOP as OOP was to procedural programming Not a replacement for OOP, rather a superset of OO. i.e. every valid Java program is also a valid AspectJ program. Complementary to the XP process as well YAGNI “You Aren’t Gonna Need It”: Always implement things when you actually need them, never when you just foresee that you need them (C2.com, 2004).

AOP Terminology Common terms in AOP (Gradecki, 2003) Joinpoint: a well-defined location within the code (primary or crosscutting) where a concern can crosscut. Method calls, method execution, constructor calls, constructor execution, field access (read or write), exception handler execution, etc. Pointcut: a set of join points. Can be named or anonymous When a pointcut is matched, advice can be executed.

AOP Terminology Advice: code to be executed when a pointcut is matched. Can be executed before, around, or after a particular join point. Analogous to event-driven database triggers. Aspect: container holding point cuts & advice Analogous to a class holding methods and attributes. Weaver: the tool that instruments the primary concerns with the advice based on matched pointcuts.

AOP Terminology Object Oriented Aspect Oriented Class – code unit that encapsulates methods and attributes. Aspect – code unit that encapsulates pointcuts, advice, and 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.

Weaving Types When can advice be inserted? 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).

Defining Pointcuts Calling methods & constructors (Laddad, 2002) 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, 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

Defining Pointcuts Field access – read or write 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 (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)

Defining Pointcuts Lexically based pointcuts Keyword within captures all join points in a class, and withincode captures all join points in a particular method. 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 (Laddad, 2002)

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 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)

Defining Pointcuts Pointcuts and logical operators Can be combined with &&, ||, and ! Ex: Capture public operations on CreditCardProcessor which take arguments of CreditCard and Money. (Laddad, 2002) pointcut cardProc(CreditCard card, Money amount): execution (public * CreditCardProcessor.*(..)) && args (card, amount);

Advices Advice executes when a pointcut matches. Three instrumentation points before: executes just prior to the join point. after: executes just after the join point. around: executes before and/or after, with the operation taking place via a call to proceed(). Note, if proceed is not called, then the advised code is skipped.

Simple bank account class 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.

Adding pre-condition checking 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)) 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");

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

Opt-in logging (AspectJ.org, 2004) Example 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() + "]"); }

Tests public 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);

Output 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.getBalance] Entering [org.thewhittakers.banking.TestAccount.tearDown] Entering [org.thewhittakers.banking.TestAccount.testBadCredit] Entering [org.thewhittakers.banking.TestAccount.printError] *** Negative amounts not permitted ***

Conclusion AOP is an evolutionary step Does not supplant OOP, but enhances it. Decomposes the system into primary and crosscutting concerns which map more directly into requirements. Increases comprehension of the system by reducing tangling and scattering. Joinpoints, pointcuts, and advice are used to instrument primary concerns with crosscutting concerns.

Questions Download presentation and examples: http://www.thewhittakers.org/~todd/AOP.zip Questions? Comments? Experiences?

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.