390 likes | 620 Views
Spring 2012. Introduction to Aspect-Oriented Programming. CS 3360 Gregor Kiczales, et. al. Getting started with AspectJ, CACM , 44(10):59-65, October 2001. Outline. Motivation Aspect-oriented programming A taste of AOP with AspectJ. Logging…. Where is logging in some large server code?
E N D
Spring 2012 Introduction to Aspect-Oriented Programming CS 3360 Gregor Kiczales, et. al. Getting started with AspectJ, CACM, 44(10):59-65, October 2001.
Outline • Motivation • Aspect-oriented programming • A taste of AOP with AspectJ
Logging… • Where is logging in some large server code? • red shows lines of code that handle logging • not in just one place • not even in a small number of places Not Modularized!
Questions • Other things like this? • Why is it bad to handle this all over the code?
Separation of Concerns • Definition. A concern is a specific requirement or consideration that must be addressed in order to satisfy the overall system goal. • Two kinds of concerns • Core concerns: central functionality (e.g., business logic) • Crosscutting concerns: system-level, peripheral requirements that cross multiple modules (e.g., logging)
Business logic Concerns system Logging Persistence Implementation modules Current Approach • No support for separate concern implementation
The Problem of Crosscutting Concerns • Code tangling • Module handling multiple concerns simultaneously Logging Business logic Other concern
The Problem • Code scattering • Single issue implemented in multiple modules Logging Internet banking Accounting Teller Customer
Can We Do Better? Clear Crosscutting Structure • All modules use the trace facility in a consistent way, i.e., entering methods and exiting methods. TraceSupport
Tracing as Aspect // pseudo code aspect MyTracing before method execution do: indicate beginning of execution after method execution do: indicate end of execution TraceSupport
The Idea of AOP • Crosscutting is inherent in complex systems • Crosscutting concerns have: • Clear purpose • Natural structure, e.g., defined set of methods, module boundary crossings, points of resource utilization, and lines of dataflow. • So, why not capture the structure of crosscutting concerns explicitly? • in a modular way • with linguistic and tool support • Aspects are well-modularized crosscutting concerns
An Overview of AspectJ • Supports Aspect OP • A small extension to Java • A general-purpose AOP language • Just as Java is a general-purpose OO language • Active research community: conferences, journals, books, software, etc. • URL: http://www.aspectj.org
Components of Aspect-j • Join points • Pointcuts • Advices • Aspects
First AspectJ Program • Crosscutting HelloWorld program public class HelloWorld { public void say(String msg) { System.out.println(msg); } public static void main(String [] args) { new HelloWorld().say(“Hello, world!”); } }
Crosscutting HelloWorld public aspect MilitaryProtocol { pointcut sayPoint() : execution (void HelloWorld.say(String)); after() : sayPoint() { System.out.println("Over!"); } }
Compiling and Running % javac HelloWorld.java % java HelloWorld Hello, world! % ajc HelloWorld.java MilitaryProtocol.aj % java HelloWorld Hello, world! Over!
Anatomy of MiltaryProtocol public aspect MilitaryProtocol { pointcut sayPoint() : execution (void HelloWorld.say(String)); after() : sayPoint() { System.out.println("Over!"); } } pointcut declaration aspect definition advice definition
Definitions • Join points • Well-defined points in execution of program • Pointcuts • A means to referring to collections of join points and certain values at those join points • E.g., pointcut sayPoint() : execution (void HelloWorld.say(String)); • Advices • Method-like constructs used to define additional behavior at join points • E.g., after() : sayPoint() { System.out.println("Over!"); • Aspects • Units of modular crosscutting implementation, composed of pointcuts, advice, and ordinary Java member declarations.
Components of AOP Languages • Join point model • Ways to designate a set of join points • Ways to define additional actions to be performed at join points
Join Points (cont’d) • Several kinds of join points • Method and constructor call • Method and constructor body execution • Reading (getting) a field • Writing (setting) to a field • Initialization of an object • Static initialization of a class • Exception handling
Pointcut • Denotes a set of join points, e.g., execution(void HelloWorld.say(String)) execution(void HelloWorld.*(String)) execution(* *.*(..))
Advice • Code that is attached to a pointcut and can be run: - before - after each join point in the pointcut.
Advice (cont’d) before() : execution (void HelloWorld.say(String)) { System.out.println(“Good day!”); } after() : execution (void HelloWorld.say(String)) { System.out.println(“Over!”); }
after before Semantics of Advices a HelloWord dispatch
Aspects • Similar to Java classes • Units of modular crosscutting implementation, composed of pointcuts, advice, and ordinary Java member declarations. import java.io.*; public aspect MilitaryProtocol { pointcut sayPoint() : execution (void HelloWorld.say(String)); after() : sayPoint() { endMSG(System.out); } private void endMSG(PrintStream out) { out.println(END_OF_MSG); } private static final String END_OF_MSG = “Over!”; }
class Book { private String title; private String author; private String isbn; private PostScript ps; private User borrower; public Book(String t, String a, String i, PostScript p) { title = t; author = a; isbn = i; ps = p; } public User get_borrower() {return borrower;} public void set_borrower(User u) {borrower = u;} public PostScript get_ps() { return ps; } } public class PrinterImpl { String status = “Idle” Vector jobs; public PrinterImpl() {} pubilc get_status() { return status } public add_job(int j) { jobs.add(j); } } executable code classes class User { private String name; Library theLibrary; Printer the; Printer public User(String n) { name = n; } public boolean getBook (String title) { Book aBook = theLibrary.getBook(this, title); thePrinter.print(this,aBook); return true; } } class Library { Hashtable books; Library(){ books = new Hashtable(100); } public Book getBook(User u, String title) { System.out.println("REQUEST TO GET BOOK " + title); if(books.containsKey(title)) { Book b = (Book)books.get(title); System.out.println("getBook: Found it:" + b); if (b != null) { if (b.get_borrower() == null) b.set_borrower(u); return b; } } return null; } } aspect weaver portal Printer { void print(Book book) { book: Book: {direct pages;} } portal Library { Book find (String title){ return: Book: {copy title, author, isbn;} } } aspects How Does It Work? • Aspect weaver combines classes and aspects • compiler / pre-processor / interpreter • unambiguously coordinates cross-cutting
Typical Uses of AOP • Modularizing large programs (new behaves as the old code), e.g., exception handling in telecom code • Modularizing to add new behavior (superimpose new behavior on old code), e.g., add authentication to a program • Support of product lines (new code is a variant in some aspects), e.g., add code to control new airplane • Support performance improvements (treat special cases faster), e.g., bypass code for unused network layers
Summary - Promise of AOP • Modular separation of concerns • Crosscutting concerns confined to single modules • Thus systems are • Easier to understand, • Easier to change, adapt, evolve, and reuse • Can add/remove spectators and change behavior without editing existing code.
Exercise Define an aspct to change the behavior of HelloWorld class to salute with “Sir,” before “say”ing anything. public class HelloWorld { public void say(String msg) { System.out.println(msg); } public static void main(String [] args) { new HelloWorld().say(“Hello, world!”); } }
Exercise Given the following Java class, write AspectJ code that ignores every 10th call to the setValue method. public class Counter { private int value; public void setValue(int value) { this.value = value; } public int getValue() { return value; } }
Exercise (Take-Home) Given the following Java class, write AspectJ code that prints the old and the new values of the counter whenever the value is changed. public class Counter { private int value; public void setValue(int value) { this.value = value; } public int getValue() { return value; } }
Around Advice • Advice that is run as follows: • It is called before a join point • It can decide to proceed (delegate) • When the proceed returns, it can perform more actions
Around Advice (cont’d) void around() : execution (void HelloWorld.say(String)) { System.out.println(“Good day!”); if (Math.random() > 0.5) { proceed(); } System.out.println(“Over!”); }
around Semantics of Around Advices a HelloWord dispatch