Title: Aspect Oriented Programming Programming Languages Seminar Presenter: Baris Aktemur 18 Feb' 2004
1Aspect Oriented ProgrammingProgramming
Languages SeminarPresenter Baris Aktemur18
Feb. 2004
Mostly taken from Bedir Tekinerdogans slides
2Outline
- Introduction
- Problems
- Terminology
- Aspect-Oriented Programming Languages/Frameworks
- Compositional Filters
- AspectJ
- Hyper/J
- DemeterJ
- Conclusions
3Introduction
- Evolution of Programming Languages
- Assembly/Machine Languages
- Formula Translation
- Procedural Programming
- Structured Programming
- Functional Programming
- Logic Programming
- Programming with abstract data types
- Evolution of Software Design
- Monolithic ---gt Modular
4Design Principles ? Modularity
- Abstraction
- Focus only on relevant properties
- Decomposition
- Divide software into separately named and
addressable modules - Encapsulation
- Group related things together.
- Information Hiding
- Hide implementation details from the outside
- Separation of Concerns
- Ensure that each module only deals with one
concern - Low Coupling
- aim for low coupling among the modules
- High Cohesion
- aim for high cohesion within one module
5Separation of Concerns
- Cohesion
- Maximize cohesion within a component
- i.e. Cohesive component performs only one
concern/task - required changes can be easily localized and will
not propagate - Coupling
- Highly coupled components have many
dependencies/interactions - Minimize coupling between components
- reduces complexity of interactions
- reduces ripple effect
6Advantages of separation of concerns
- Understandability
- Maintainability
- Extensibility
- Reusability
- Adaptability
Separation of Concerns directly supports quality
factors. Lack of Separation of Concerns
negatively impacts quality factors.
7Example - Figure Editor
- A figure consists of several figure elements. A
figure element is either a point or a line.
Figures are drawn on Display. A point includes X
and Y coordinates. A line is defined as two
points.
8Example - Figure Editor - Design
- Components are
- Cohesive
- Loosely Coupled
- Have well-defined interfaces (abstraction,
encapsulation)
Nice Modular Design!
9Crosscutting Concern - Example
Notify ScreenManager if a figure element moves
Display
Figure
FigureElement
Point
Line
2
getX() getY()
getP1 setP1
setX(int) setY(int)
setP1(Point) setP2(Point)
10Example Display Tracking
Crosscutting Concern
class DisplayTracker static void
updatePoint(Point p) this.display(p) ....
static void updateLine(Line l)
this.display(l) ....
DisplayTracker
class Point void setX(int x)
DisplayTracker.updatePoint(this) this.x
x
class Line void setP1(Point p1
DisplayTracker.updateLine(this) this.p1
p1
11Example - Tracing - Design
Trace the execution of all operations...
Tracer
traceEntry traceExit
Tracing
12Example - Tracing
Scattered Concern
Tangling Code
class Tracer static void traceEntry(String
str) System.out.println(str) static
void traceExit(String str)
System.out.println(str)
Tracer
class Point void setX(int x) _x x
class Line void setP1(Point p1 _p1
p1
13Example Tracing and Display Tracking
Tracer
trace
14Crosscutting, Scattering and Tangling
- Crosscutting
- concern that inherently relates to multiple
components. - results in scattered concern and tangled code
- non-functional requirements likely to crosscut
- Scattering
- Single concern affects multiple modules
- Tangling
- multiple concerns are interleaved in a single
module
15Example of crosscutting concerns
- Synchronization
- Real-time constraints
- Error-checking
- Object interaction constraints
- Memory management
- Persistency
- Security
- Caching
- Logging
- Monitoring
- Testing
- Domain specific optimization
- ...
16Aspect-Oriented Software Development
- Provides better separation of concerns by
explicitly considering crosscutting concerns (as
well) - Does this by providing explicit abstractions for
representing crosscutting concerns, i.e. aspects - and composing these into programs, i.e. aspect
weaving or aspect composing. - As such AOSD improves modularity
- and supports quality factors such as
- maintainability
- adaptability
- reusability
- understandability
- ...
17Basic AOP technologies
- Composition Filters
- University of Twente, The Netherlands
- AspectJ
- XEROX PARC, US
- DemeterJ/DJ
- Northeastern University, US
- Multi-dimensional separation of Concerns/HyperJ
- IBM TJ Watson Research Center, US
18History of AOP languages
Scripts (Francez 81)
OO languages
MOP(1985)
Reflection(Smith 81)
Sinainterface predicates(1988)
AI (semanticnetworks 79)
Law of Demeter(1988)
CLOS-MOP
Adaptiveprogramming(1992)
Crosscuttingaspects (1996)
Composition Filters(1992)
AspectJ(1997)
Composition Filterswith superimposition(2001)
AspectJ(2000)
http//trese.cs.utwente.nl
19Composition Filters
Ref http//trese.cs.utwente.nl
20Example - Mail System
21Interface of EMail
Class Email interfaceputOriginator(anOriginator)
getOriginator returns anOriginatorputReceiver(a
Receiver)getReceiver returns aReceiverputConte
nt(aContent)getContent returns
aContentsendreplyapproveisApproved
returns BooleanputRoute(aRoute)getRoute
returns aRoutedeliverisDelivered returns
Boolean
22Multiple Views
- Not all operations of mail should be generally
applicable. We can distinguish between the
following views - User view
- originator, receiver
- System view
- postman, mail system
23USViewMail extends EMail
- putOriginator
- putReceiver
- putContent
- getContent
- send
- reply
Mail
USViewMail
system view
- getOriginator
- getReceiver
- isApproved
- getRoute
- isDelivered
user view
24Implementation of USViewMail
EMail
To reuse the operations of EMail, USViewMail may
inherit from it.
USViewMail
putOriginator(anOriginator) if self.userView
then super.putOriginator(anOriginator)
else self.error
userView return client.category user
25Implementation of USViewMail
USViewMail
Here is the second option! To reuse the
operations of EMail, USViewMail may aggregate an
instance of EMail and redirect the calls to this
object.
ImpEMail
putOriginator(anOriginator) if self.userView
then imp.putOriginator(anOriginator)
else self.error
userView return client.category user
26Identify of the client object
Wait a minute! How does the server detect the
identity of the client object?
The server object must test the id of the client
object. This is not always easy!
In languages like C and Java, this information
is generally not accessible by the programmer.
The client can pass the id but then the call will
have an extra argument in some languages this is
considered as a different call.
This is what one might calllack of expression
power problem!
userView return client.category user
27Implementation of USViewMail
Lets assume that userViewcan be computed. I want
to evaluate the inheritance-based implementation.
All these 9 operations must be re-defined! 2
operations for the views, in total 11
new operations must be defined!
The remaining 5operations are inherited!
6 x user views
3 x system views
28Implementation USViewMail
In the aggregation-basedimplementation to add 2
views, 16 operations must be defined!
These are 6 user and 3 system views 2
viewimplementations and 5 forwarding 16
operations.
6 x user views
3 x system views
5 x forwarding
29Evolution Scenario
USViewMail is not the only possible extension to
EMail. As an example, I will introduce the
following classes as extensions ORViewMail,
WarningMail, LockingMail, DynamicMail
Monitoring. Lets try to reuse the classes as
much as possible
30Evaluation
- Many operations must be redefined to implement a
new scenario. - Duplication
- Because of Not-Separated Concerns (Crosscutting
and tangling)
31Filters are modular extensions
- In case more than one concern
- is needed, multiplefilters can be used.
Instead of providingdedicated solutionsby
modifyingclass descriptions, Composition
Filtersoffers modular extensions toclass
abstractionsexpressed in languages likeJava,
C and Smalltalk.
- Each filter transforms incomingand/or outgoing
messagesto/from object.
a filter
A modularextension
32Implementation of USViewMail using CFs
Filter multipleViews
Filter invoke
userView systemview
Assume that USViewMail aggregatesEmail for
reuse. In addition, 2 filters called
multipleViews and invoke,and two new operations
userView and systemVieware defined.
33USViewMail using CFs (conted)
This is thespecificationof the first filter!
multipleViews Error
userView gt putOriginator, putReceiver,
putContent, getContent, send, reply,
systemView gt approve, putRoute, deliver,
True gt getOriginator, getReceiver, isApproved,
getRoute, isDelivered
34USViewMail using CFs (conted)
match
False
multipleViews Error
userView gt putOriginator, putReceiver,
putContent, getContent, send, reply,
userView
systemView gt approve, putRoute, deliver,
systemView
True gt getOriginator, getReceiver, isApproved,
getRoute, isDelivered
True
35USViewMail using CFs (conted)
no match
ERROR
True
no match
multipleViews Error
False
userView gt putOriginator, putReceiver,
putContent, getContent, send, reply,
userView
systemView gt approve, putRoute, deliver,
systemView
True gt getOriginator, getReceiver, isApproved,
getRoute, isDelivered
36Evaluation of USViewMail
Filter multipleViews
Filter invoke
userView systemview
In CF basedimplementation to add 2 views, 2
filters and 2 operationshas to be defined!
2 x filters
2 x operations
37USViewMail filter interface
filterinterface USViewMail begin internals
mail Mail conditions userView
systemView inputfilters mv Error
userView gt putOriginator, putReceiver,
putContents, getContents, send,
systemView gt approve, deliver, putRoute,
true gt getOriginator,
getReceiver, isApproved,
getRoute, isDelivered
invoke Dispatch true gt inner., mail.
end interface
38Filter Types and Semantics
39AspectJ
- A general purpose AO programming language
- just as Java is a general-purpose OO language
- unlike examples in ECOOP97 paper
- domain specific languages for each aspect
- an integrated extension to Java
- accepts all java programs as input
- outputs .class files compatible with any JVM
- integrated with tools
40Example Without AOP
class Line private Point _p1, _p2 Point
getP1() return _p1 Point getP2() return
_p2 void setP1(Point p1)
Tracer.traceEntry(entry setP1) _p1 p1
Tracer.traceExit(exit setP1) void
setP2(Point p2) Tracer.traceEntry(entry
setP2) _p2 p2 Tracer.traceExit(exit
setP2) class Point private int _x 0,
_y 0 int getX() return _x int getY()
return _y void setX(int x)
Tracer.traceEntry(entry setX) _x x
Tracer.traceExit(exit setX) void setY(int
y) Tracer.traceEntry(exit setY)
_y y Tracer.traceExit(exit setY)
class Tracer static void traceEntry(String
str) System.out.println(str) static
void traceExit(String str)
System.out.println(str)
Tangling Code
Scattered Concern
41Example With AOP
class Line private Point _p1, _p2 Point
getP1() return _p1 Point getP2() return
_p2 void setP1(Point p1) _p1 p1
void setP2(Point p2) _p2 p2
class Point private int _x 0, _y
0 int getX() return _x int getY()
return _y void setX(int x) _x
x void setY(int y) _y y
aspect Tracing pointcut traced() call(
Line. call( Point.) before()
traced() println(Entering
thisjopinpoint) void println(String str)
ltwrite to appropriate streamgt
Aspect is defined in a separate
module Crosscutting is localized No scattering
No tangling Improved modularity
42Aspect Language Elements
- join point (JP) model
- certain principled points in program execution
such as method calls, field accesses, and object
construction - means of identifying JPs
- picking out join points of interest (predicate)
- pointcuts set of join points
- means of specifying behavior at JPs
- what happens
- advice declarations
43Modularizing Crosscutting
- Joinpoints any well-defined point of execution
in a program such as method calls, field
accesses, and object construction - Pointcut predicate on joinpoints selecting a
collection of joinpoints.
Tracer
pointcut traced() call( Line.)
call( Point.)
44Joinpoints
- method call join points
- when a method is called
- method reception join points
- when an object receives a message
- method execution join points
- when the body of code for an actual method
executes - field get joint point
- when a field is accessed
- field set joint point
- when a field is set
- exception handler execution join point
- when an exception handler executes
- object creation join point
- when an instance of a class is created
45Some primitive pointcuts
- call(Signature)
- picks out method or constructor call based on
Signature - execution(Signature)
- picks out a method or constructor execution join
point based on Signature - get(Signature)
- picks out a field get join point based on
Signature - set(Signature)
- picks out a field set join point based on
Signature - handles(TypePattern)
- picks out an exception handler of any of the
Throwable types of TypePattern - instanceOf(ClassName)
- picks out join points of currently executing
objects of class ClassName - within(ClassName)
- picks out join points that are in code contained
in ClassName - withinCode(Signature)
- picks out join points within the member defined
by methor or constructor (Signature)
46Advice
- Piece of code that attaches to a pointcut and
thus injects behavior at all joinpoints selected
by that pointcut. - example
- before (args) pointcut Body
- where before represents a before advice type (see
next slide). - Can take parameters with pointcuts
47Advice Types
- Advice code executes
- before, code is injected before the joinpoint
- before (args) pointcut Body
- after, code is injected after the joinpoint
- after (args) pointcut Body
- around, code is injected around (in place of)
code from joinpoint - ReturnType around (args) pointcut Body
48Aspect
- A modular unit of cross-cutting behavior.
- Like a class, can have methods, fields,
initializers. - can be abstract, inherit from classes and
abstract aspects and implement interfaces. - encapsulates pointcuts and advices
- can introduce new methods / fields to a class
AspectX
AspectX
classX
x
classY
AspectY
AspectY
49Example - AspectJ
class Line private Point _p1, _p2 Point
getP1() return _p1 Point getP2() return
_p2 void setP1(Point p1) _p1 p1
void setP2(Point p2) _p2 p2
class Point private int _x 0, _y
0 int getX() return _x int getY()
return _y void setX(int x) _x
x void setY(int y) _y y
aspect Tracing pointcut traced() call(
Line. call( Point.) before()
traced() println(Entering
thisjopinpoint) after() traced()
println(Exit thisjopinpoint) void
println(String str) ltwrite to appropriate
streamgt
aspect
50Code Weaving
- Before compile-time (pre-processor)
- During compile-time
- After compile-time
- At load time
- At run-time
51Example - AspectJ
aspect MoveTracking private static boolean
_flag false public static boolean
testAndClear() boolean result _flag
_flag false return result pointcut
moves() receptions(void Line.setP1(Point))
receptions(void Line.setP2(Point))
static after() moves() _flag true
52HyperJ
53HyperJ - multi dimensional
54Multi Dimensional Separation of Concerns
- Not that simple!
- Composition Strategies
- merge by name
- Automatic matching based on name and type
- Matching units are merged ( combined so all have
a presence in the combined result - override by name
- Automatic matching based on name and type
- Classes are merged, but for members that have the
same, the last overrides the others - non-corresponding merge
- No automatic matching
- Units in different slices are not to correspond
- Names are accidentally the same
55HyperJ / MDSOC definition
56DemeterJ / DJ
- Law Of Demeter
- Each unit should only have limited knowledge
about other units only about units closely
related to the current unit. - Each unit should only talk to its friends.
- Dont talk to strangers.
- Goal Reduce behavioral dependencies between
classes. - Loose coupling
57Applying LoD
- A method must be able to traverse links to obtain
its neighbors and must be able to call operations
on them. - But it should not traverse a second link from the
neighbor to a third class. - Methods should communicate only with preferred
suppliers - immediate parts on this
- objects passed as arguments to method
- objects which are directly created in method
- objects in global variables
- No other calls allowed
- ---gt Scattering
58Solution is Adaptive Programming
- Encapsulate operation into one place thereby
avoiding scattering - Specify traversal over (graph) structure in a
succinct way thereby reducing tangling. - Navigation strategy
59Use of Visitors
- import edu.neu.ccs.demeter.dj.
- // define strategy
- String strategyfrom BusRoute through BusStop to
Person - class BusRoute
- // define class graph
- static Classgraph cg new ClassGraph()
- int printCountWaitingPersons() //
traversal/visitor weaving - //define visitor
- Visitor v new Visitor()
- public void before(Person host) r
- public void start() r 0
-
-
- cg.traverse(this, strategy, v)
- ...
-
60Advantages of DJ
- Use of reflection
- No need for source code (no code weaving)
- Can work on class files
- Purely Java (no new structure)
61Conclusion
62Key issues (6 Cs) - Mehmet Aksit
- Crosscutting
- Canonicality
- for the stability of the implementation of the
concerns - Composability
- for providing quality factors such as
adaptability, reusability, extensibility - Computability
- for creating executable software systems
- Closure Property
- for maintaining the quality of design and
implementation models - Certifiability
- for evaluating and controlling the quality of
design and imp. models
63Key Issues (4 Ss) - Harold Ossher
- Simultaneous
- Coexistence of different decompositions
- Self-contained
- Each module should declare what it depends on
- Symmetric
- There should be no difference in form between
modules (composability and closure) - Spontaneous
- possibility to identify and encapsulate new
concerns during the software life cycle.
64Future
- There are open-issues
- UML representation of aspects
- Identifying aspects early in the software
development - Aspectual refactoring
- Semantic correctness of aspects and compositions
- Serious research going on AOP
65References
- B. Tekinerdogan, CS586 Course Slides, Bilkent
University, Ankara, Turkey - Communications of the ACM, Aspect Oriented
Programming, Volume 44, Number 10, Oct. 2001 - http//trese.cs.utwente.nl/composition_filters
- http//trese.cs.utwente.nl/taosad/
- M. Aksit, L. Bergmans B. Tekinerdogan.
Aspect-Composition using Composition Filters, in
Software Architectures and Component Technology
The State of the Art in Research and Practice, M.
Aksit (Ed.), Kluwer Academic Publishers, pp. 357
- 382, 2001. - G.Kiczales, J. Lamping, A.Mendhekar, C. Lopes, J.
Loingtier, J. Irwin. Aspect-Oriented Programming,
European Conference on Object-Oriented
Programming (ECOOP), Springer-Verlag, LNCS 1241,
June 1997. - Gregor Kiczales, Erik Hilsdale, Jim Hugunin, Mik
Kersten, Jeffrey Palm, and William G. Griswold.
An Overview of AspectJ. In J. Lindskov Knudsen
(ed.), ECOOP 2001 Object-Oriented Programming
15th European Conference, Budapest Hungary, pages
327-353. Volume 2072 of Lecture Notes in Computer
Science, Springer-Verlag, Berlin, June, 1997. - P. Tarr, H. Ossher, W. Harrison and S.M. Sutton,
Jr. "N Degrees of Separation Multi-Dimensional
Separation of Concerns." Proceedings of the
International Conference on Software Engineering
(ICSE'99), May, 1999 - Karl Lieberherr and Doug Orleans and Johan
Ovlinger, Aspect-Oriented Programming with
Adaptive Methods . Northeastern University Tech
Report, NU-CCS-2001-02 - D. Stein, S. Hanenberg, R. Unland. A UML-based
Aspect-Oriented Design Notation for AspectJ, in
G. Kiczales (ed.), Proc. of First ACM
International Conference on Aspect-Oriented
Software Development, Enschede, The Netherlands,
April, 2001.
66Thank you!