Sunday, February 17, 2008

Aspect-Oriented Programming and Introduction to AspectJ


Aspect-Oriented ProgrammingIntroduction to AspectJ
Programming paradigms
• Procedural programming
– Executing a set of commands in a given sequence
– Fortran, C, Cobol
• Functional programming
– Evaluating a function defined in terms of other functions
– Lisp, ML, OCaml
• Logic programming
– Proving a theorem by finding values for the free variables
– Prolog
• Object-oriented programming (OOP)
– Organizing a set of objects, each with its own set of responsibilities
– Smalltalk, Java, C++ (to some extent)
• Aspect-oriented programming (AOP)
– Executing code whenever a program shows certain behaviors
– AspectJ (a Java extension)
– Does not replace O-O programming, but rather complements it



Introduction• Currently, the dominant programming paradigm is object-oriented programming that:
• Object orientation is a clever idea, but has certain limitations
• has been presented as a technology that can fundamentally aid software engineering
• is reflected in the entire spectrum of current software development methodologies and tools


Introduction AOP
• A new programming technique called aspect-oriented programming (AOP):
- makes it possible to clearly express those programs that OOP fail to support
- enables the modularization of crosscutting concerns by supporting a new unit of

software modularity – aspects – that provide encapsulation for crosscutting concerns

What are aspects?• The current working definition is (May 99, Gregor Kiczales):
- modular units that cross-cut the structure of other modular units
- units that is defined in terms of partial information from other units
- exist in both design and implementation

Aspect: A distinct feature or element in a problem

Concerns• AOP is based on the idea that computer systems are better programmed by separately specifying the various concerns of a system
• Separation of concerns is an important software engineering principle guiding all stage of a software development methodology
• Concerns:
are properties or areas of interest
can range from high-level notion to low level-notion
can be functional or nonfunctional (systemic)

The problem
• Some programming tasks cannot be neatly encapsulated in objects, but must be scattered throughout the code
• Examples:
– Logging (tracking program behavior to a file)
– Profiling (determining where a program spends its time)
– Tracing (determining what methods are called when)
– Session tracking, session expiration
– Special security management
• The result is crosscuting code--the necessary code “cuts across” many different classes and methods


Example
class Fraction {
int numerator;
int denominator;
...
public Fraction multiply(Fraction that) {
traceEnter("multiply", new Object[] {that});
Fraction result = new Fraction( this.numerator * that.numerator, this.denominator * that.denominator);
result = result.reduceToLowestTerms();
traceExit("multiply", result);
return result;
}
...
}
Now imagine similar code in every method you might want to trace



Consequences of crosscutting code• Redundant code
– Same fragment of code in many places
• Difficult to reason about
– Non-explicit structure
– The big picture of the tangling isn’t clear
• Difficult to change
– Have to find all the code involved...
– ...and be sure to change it consistently
– ...and be sure not to break it by accident
• Inefficient when crosscuting code is not needed

AspectJTM
• AspectJ is a small, well-integrated extension to Java
– Based on the 1997 PhD thesis by Christina Lopes, A Language Framework for Distributed Programming
• AspectJ modularizes crosscutting concerns
– That is, code for one aspect of the program (such as tracing) is collected together in one place
• The AspectJ compiler is free and open source
• AspectJ works with JBuilder, Forté, Eclipse, probably others
• Best online writeup: http://www.eclipse.org/aspectj/


Terminology• A join point is a well-defined point in the program flow
• A pointcut is a group of join points
• Advice is code that is executed at a pointcut
• Introduction modifies the members of a class and the relationships between classes
• An aspect is a module for handling crosscutting concerns
– Aspects are defined in terms of pointcuts, advice, and introduction
– Aspects are reusable and inheritable
• Each of these terms will be discussed in greater detail
The Figure Element example




Using Objects• Expressive
– What is going on its clear
• Abstraction
– Focus on more or less detail
• Structure & Modularity
– What goes where
– How parts fit together
–Things are pretty clear, you know every thing about it. If you wanna add new shapes(FigureElement) that also you can add.
–So now lets make it probelamatic… how… Simple Observer Pattern
–If there is any change in the shape…. Drawing Object should be notified.
–So what is this , good design but a worst code.
–So what can we do , we can use aspects , we can have a aspect for observer pattern and which will be weaved with the existing codess and proviides use the way to work with new requirements.
–So we have Good Design and Good Code.
–Lets see how to do that with the help of aspects.



Other Aspects
• Security
– Pointcut for when checking happens
• Optimization
• Distribution
• Synchronization
• Persistance
• And ofcourse Logging/Tracing
• And very many application –specific aspects
- i.e EnsureLiveness

Example I• A pointcut named move that chooses various method calls:
pointcut move(): call(void FigureElement.setXY(int,int))||
call(void Point.setX(int))||
call(void Point.setY(int))||
call(void Line.setP1(Point))||
call(void Line.setP2(Point));||

• Advice (code) that runs before the move pointcut:
before(): move() {
System.out.println("About to move");
}
• Advice that runs after the move pointcut:
after(): move() {
System.out.println("Just successfully moved");
}
Join points
• A join point is a well-defined point in the program flow
– We want to execute some code (“advice”) each time a join point is reached
– AspectJ provides a syntax for indicating these join points “from outside” the actual code
• A join point is a point in the program flow “where something happens”
– Examples:
• When a method is called
• When an exception is thrown
• When a variable is accessed

AspectJ supports 11 different kinds of join points.These are the method call, method execution, constructor call, constructor execution, field get, field set, pre initialization, initialization, static initialization, handler, and advice execution join points.
Pointcuts
• Pointcut definitions consist of a left-hand side and a right-hand side, separated by a colon
– The left-hand side consists of the pointcut name and the pointcut parameters (i.e. the data available when the events happen)
– The right-hand side consists of the pointcut itself
• Example pointcut:pointcut setter(): call(void setX(int));
– The name of this pointcut is setter
– The pointcut has no parameters
– The pointcut itself is call(void setX(int))
– The pointcut refers to any time the void setX(int) method is called
Example pointcut designators I
• When a particular method body executes:
– execution(void Point.setX(int))
• When a method is called:
– call(void Point.setX(int))
• When an exception handler executes:
– handler(ArrayOutOfBoundsException)
• When the object currently executing (i.e. this) is of type SomeType:
– this(SomeType)



Example pointcut designators II• When the target object is of type SomeType
– target(SomeType)
• When the executing code belongs to class MyClass
– within(MyClass)
• When the join point is in the control flow of a call to a Test's no-argument main method
– cflow(call(void Test.main()))
Pointcut designator wildcards
• It is possible to use wildcards to declare pointcuts:
– execution(* *(..))
• Chooses the execution of any method regardless of return or parameter types
– call(* set(..))
• Chooses the call to any method named set regardless of return or parameter type
• In case of overloading there may be more than one such set method; this pointcut picks out calls to all of them
Pointcut designators based on types
• You can select elements based on types. For example,
– execution(int *())
• Chooses the execution of any method with no parameters that returns an int
– call(* setY(long))
• Chooses the call to any setY method that takes a long as an argument, regardless of return type or declaring type
– call(* Point.setY(int))
• Chooses the call to any of Point’s setY methods that take an int as an argument, regardless of return type
– call(*.new(int, int))
• Chooses the call to any classes’ constructor, so long as it takes exactly two ints as arguments
Pointcut designator composition
• Pointcuts compose through the operations or (“”), and (“&&”) and not (“!”)
• Examples:
– target(Point) && call(int *())
• Chooses any call to an int method with no arguments on an instance of Point, regardless of its name
– call(* *(..)) && (within(Line) within(Point))
• Chooses any call to any method where the call is made from the code in Point’s or Line’s type declaration
– within(*) && execution(*.new(int))
• Chooses the execution of any constructor taking exactly one int argument, regardless of where the call is made from
– !this(Point) && call(int *(..))
• Chooses any method call to an int method when the executing object is any type except Point
Pointcut designators based on modifiers• call(public * *(..))
– Chooses any call to a public method
• execution(!static * *(..))
– Chooses any execution of a non-static method
• execution(public !static * *(..))
– Chooses any execution of a public, non-static method
• Pointcut designators can be based on interfaces as well as on classes
Example I, repeated
• A pointcut named move that chooses various method calls:
pointcut move(): call(void FigureElement.setXY(int,int))
call (void Point.setX(int))
call(void Point.setY(int))
call(void Line.setP1(Point))
call(void Line.setP2(Point));

• Advice (code) that runs before the move pointcut:
before(): move() {
System.out.println("About to move");
}

• Advice that runs after the move pointcut:
after(): move() {
System.out.println("Just successfully moved");
}

Kinds of advice
AspectJ has several kinds of advice; here are some of them:
– Before advice runs as a join point is reached, before the program proceeds with the join point
– After advice on a particular join point runs after the program proceeds with that join point
• after returning advice is executed after a method returns normally
• after throwing advice is executed after a method returns by throwing an exception
• after advice is executed after a method returns, regardless of whether it returns normally or by throwing an exception
– Around advice on a join point runs as the join point is reached, and has explicit control over whether the program proceeds with the join point

Example II, with parameters• You can access the context of the join point:
• pointcut setXY(FigureElement fe, int x, int y): call(void FigureElement.setXY(int, int)) && target(fe) && args(x, y);
• after(FigureElement fe, int x, int y) returning: setXY(fe, x, y) { System.out.println(fe + " moved to (" + x + ", " + y + ").");}


Introduction
• An introduction is a member of an aspect, but it defines or modifies a member of type (class). With introduction we can
– add another methods to an existing class
– add fields to an existing class
– extend an existing class with another
– implement an interface in an existing class
– convert checked exceptions into unchecked exceptions

Example introductionpublic aspect CloneSimpleClass {
declare parents: SimpleClass2 implements Cloneable;
declare soft: CloneNotSupportedException: execution(Object clone());
public Object SimpleClass2.clone(){ return super.clone();}
}

/*
* 1. Class which does not implement CloneNotSupportedException, expected output is
* sucessful running of the method calls because we have aspect for cloning.
*/
public class SimpleClass2 {
private String name=null;
public SimpleClass2(String s){
name = s;
}
public static void main(String[] args) {
SimpleClass2 ref1 = new SimpleClass2("Demo");
ref1.funtion();
try {
SimpleClass2 ref2 = (SimpleClass2) ref1.clone();
ref2.funtion();
} catch (Exception e) {
e.printStackTrace();
}
}
private void funtion() {
System.out.println("Name is "+name);
}
}
So what this does, it adds a functionality for cloning to a non
Cloneable class. Deciding about the feature enancement
during runtime …. Amazing capability in the product….



Approximate syntax
• An aspect is: aspect nameOfAspect { body }
– An aspect contains introductions, pointcuts, and advice
• A pointcut designator is: when(signature)
– The signature includes the return type
– The “when” is call, handler, execution, etc.
• A named pointcut designator is: name(parameters): pointcutDesignator
• Advice is: adviceType(parameters): pointcutDesignator { body }
• Introductions are basically like normal Java code
Example aspect I• aspect PointWatching {
private Vector Point.watchers = new Vector();
public static void addWatcher(Point p, Screen s) { p.Watchers.add(s); }
public static void removeWatcher(Point p, Screen s) { p.Watchers.remove(s); }
static void updateWatcher(Point p, Screen s) { s.display(p); }

pointcut changes(Point p): target(p) && call(void Point.set*(int));
after(Point p): changes(p) {
Iterator iter = p.Watchers.iterator();
while ( iter.hasNext() ) {
updateWatcher(p, (Screen)iter.next());
} }}

How to identify which aspect is working


• In case of Introduction, which we applied to SimnpleClass2, aspect scope is for the class







The role of aspects in software design
• AOP aims at providing better means of addressing the well-known problem of separation of concerns
• Three basic approaches to addressing the process of separation of concerns:
Language-based approach• It is based on the definition of a set of language constructs
• Relevant concerns are identified at the problem domain and translated to aspectual construct
• The final application is obtained by weaving the primary structure with the crosscutting aspects
Framework-based approach• Provides more flexible constructs
• Concerns are materialized as aspectual classes at the framework level
• Developers can customize these aspects using the mechanism supported by the framework
• These types of framework are known as AO frameworks (explicitly engineers concerns)
Architecture-oriented approach• Early identification of concerns using architectural organizational models
• Architectural view-point involves a higher level of abstraction than the previous approaches
• It typically comprises two stages
Architecture-oriented approach
• First, developers should determine the problem architecture
• Then, the approach enables several kinds of aspect materialization through different frameworks



Concluding remarks• Aspect-oriented programming (AOP) is a new paradigm--a new way to think about programming
• AOP is somewhat similar to event handling, where the “events” are defined outside the code itself
• AspectJ is not itself a complete programming language, but an adjunct to Java
• AspectJ does not add new capabilities to what Java can do, but adds new ways of modularizing the code
• AspectJ is free, open source software
• AspectJ based on Java Features and which includes
– Annotations
– Generics
– Enumerated Types
– AutoBoxing and UnBoxing
– New Reflection Interfaces
– Load Time Weaving


Will be adding few exampls ............. shortly..........

1 comment:

  1. Hi nice collection of articles.Provided better idea of Understanding aspects. I would be great if you can provide some article on Security using AOP something liker a blend of Acegi and Spring using AOP..Can You Provide me some sampes related to the Logging Interceptors for Proxy classes..

    ReplyDelete