- Aspect-oriented programming
Aspect-oriented programming (AOP) is a
programming paradigm that increases modularity by allowing the separation ofcross-cutting concern s.Separation of concerns entails breaking down a program into distinct parts (so-called "concerns", cohesive areas of functionality). All programming paradigms support some level of grouping andencapsulation of concerns into separate, independent entities by providing new abstractions (e.g. procedures, modules, classes, methods) that can be used to represent these concerns. But some concerns defy these forms of encapsulation and are called "crosscutting concerns" because they "cut across" multiple abstractions in a program.Logging is the archetypal example of a crosscutting concern because a logging strategy necessarily affects every single logged part of the system. Logging thereby "crosscuts" all logged classes and methods.
All AOP implementations have some crosscutting expressions that encapsulate each concern in one place. The difference between implementations lies in the power, safety, and usability of the constructs provided. For example, interceptors that specify the methods to intercept express a limited form of crosscutting, without much support for type-safety or debugging.
AspectJ has a number of such expressions and encapsulates them in a special class, an aspect. For example, an aspect can alter the behavior of the base code (the non-aspect part of a program) by applying advice (additional behavior) at variousjoin point s (points in a program) specified in a quantification or query called apointcut (that detects whether a given join point matches). An aspect can also make binary-compatible structural changes to other classes, like adding members or parents.History
Gregor Kiczales and his team atXerox PARC originated the concept of AOP. This team also developed the first and most popular general-purpose language that supported AOP,AspectJ . IBM's research team emphasized the continuity of the practice of modularizing concerns with past programming practice, and offered the more powerful (but less usable) HyperJ andConcern Manipulation Environment , which have not seen wide usage. The examples in this article useAspectJ as it is the most widely known.Motivation and basic concepts
Some code is "scattered" or "tangled", making it harder to understand and maintain. It is scattered when one concern (like logging) is spread over a number of modules (e.g., classes and methods). That means to change logging can require modifying all affected modules. Modules end up tangled with multiple concerns (e.g., account processing, logging, and security). That means changing one module entails understanding all the tangled concerns.
For example, consider a banking application with a conceptually very simple method for transferring an amount from one account to another [Note: The examples in this article appear in a syntax that is similar to that of the Java programming language.] :
However, this transfer method overlooks certain considerations that would be necessary for a deployed application. It requires security checks to verify that the current user has the authorization to perform this operation. The operation should be in a
database transaction in order to prevent accidental data loss. For diagnostics, the operation should be logged to the system log. And so on. A simplified version with all those new concerns would look somewhat like this:In the previous example other interests have become "tangled" with the basic functionality (sometimes called the "business logic concern"). Transactions, security, and logging all exemplify "cross-cutting concerns".
Also consider what happens if we suddenly need to change (for example) the security considerations for the application. In the program's current version, security-related operations appear "scattered" across numerous methods, and such a change would require a major effort.
Therefore, we find that the cross-cutting concerns do not get properly encapsulated in their own modules. This increases the system complexity and makes evolution considerably more difficult.
AOP attempts to solve this problem by allowing the programmer to express cross-cutting concerns in stand-alone modules called "aspects". Aspects can contain advice (code joined to specified points in the program) and inter-type declarations (structural members added to other classes). For example, a security module can include advice that performs a security check before accessing a bank account. The
pointcut defines the times (join point s) that a bank account can be accessed, and the code in the advice body defines how the security check is implemented. That way, both the check and the places can be maintained in one place. Further, a good pointcut can anticipate later program changes, so if another developer creates a new method to access the bank account, the advice will apply to the new method when it executes.Join point models
The advice-related component of an aspect-oriented language defines a join point model (JPM). A JPM defines three things:
* When the advice can run. These are called "
join point s" because they are points in a running program where additional behavior can be usefully joined. A join point needs to be addressable and understandable by an ordinary programmer to be useful. It should also be stable across inconsequential program changes in order for an aspect to be stable across such changes. Many AOP implementations support method executions and field references as join points.
* A way to specify (or "quantify") join points, called "pointcut s". Pointcuts determine whether a given join point matches. Most useful pointcut languages use a syntax like the base language (e.g., Java signatures are used forAspectJ ) and allow reuse through naming and combination.
* A means of specifying code to run at a join point. InAspectJ , this is called "advice", and can run before, after, and around join points. Some implementations also support things like defining a method in an aspect on another class.Join point models can be compared based on the join points exposed, how join points are specified, the operations permitted at the join points, and the structural enhancements that can be expressed.
AspectJ's join point model
* The join points in
AspectJ include method or constructor call or execution, the initialization of a class or object, field read and write access, exception handlers, etc. They do not include loops, super calls, throws clauses, multiple statements, etc.* Pointcuts are specified by combinations of "primitive pointcut designators" (PCDs).
:"Kinded" PCDs match a particular kind of join point (e.g., method execution) and tend to take as input a Java-like signature. One such pointcut looks like this:
execution(* set*(*))
:This pointcut matches a method-execution join point, if the method name starts with "
set
" and there is exactly one argument of any type."Dynamic" PCDs check runtime types and bind variables. For example
this(Point)
:This pointcut matches when the currently-executing object is an instance of class
Point
. Note that the unqualified name of a class can be used via Java's normal type lookup."Scope" PCDs limit the lexical scope of the join point. For example
within(com.company.*)
: This pointcut matches any join point in any type in the
com.company
package. The "*
" is one form of the wildcards that can be used to match many things with one signature.Pointcuts can be composed and named for reuse. For example
pointcut set() : execution(* set*(*) ) && this(Point) && within(com.company.*);
:This pointcut matches a method-execution join point, if the method name starts with "
set
" andthis
is an instance of typePoint
in thecom.company
package. It can be referred to using the name "set()
".* Advice specifies to run (before, after, or around) at a join point (specified with a pointcut) certain code (specified like code in a method). Advice is invoked automatically by the AOP runtime when the pointcut matches the join point. Here is an example of this: after() : set() { Display.update(); }::This is effectively saying, "if the "
set()
" pointcut matches the join point, run the codeDisplay.update()
after the join point completes."Other potential join point models
There are other kinds of JPMs. All advice languages can be defined in terms of their JPM. For example a hypothetical aspect language for UML may have the following JPM:
* Join points are all model elements.
* Pointcuts are some boolean expression combining the model elements.
* The means of affect at these points are a visualization of all the matched join points.
Inter-type declarations
"inter-type declarations" provide a way to express crosscutting concerns affecting the structure of modules. Also known as
open class es, this enables programmers to declare in one place members or parents of another class, typically in order to combine all the code related to a concern in one aspect. For example, if the crosscutting display-update concern were instead implemented using visitors, an inter-type declaration using thevisitor pattern looks like this in AspectJ::This code snippet adds the
acceptVisitor
method to thePoint
class.It is a requirement that any structural additions be compatible with the original class, so that clients of the existing class continue to operate, unless the AOP implementation can expect to control all clients at all times.
Implementation
There are two different ways AOP programs can affect other programs, depending on the underlying languages and environments: (1) a combined program is produced, valid in the original language and indistinguishable from an ordinary program to the ultimate interpreter; and (2) the ultimate interpreter or environment is updated to understand and implement AOP features. The difficulty of changing environments means most implementations produce compatible combination programs through a process that has come to be known as "weaving". The same AOP language can be implemented through a variety of weaving techniques, so the semantics of a language should never be understood in terms of the weaving implementation. Only the speed of an implementation and its ease of deployment are affected by which method of combination is used.
Source-level weaving can be implemented using preprocessors (as C++ was implemented originally in
CFront ) that require access to program source files. However, Java's well-defined binary form enables bytecode weavers to work with any Java program in .class-file form. Bytecode weavers can be deployed during the build process or, if the weave model is per-class, during class loading.AspectJ started with source-level weaving in 2001, delivered a per-class bytecode weaver in 2002, and offered advanced load-time support after the integration ofAspectWerkz in 2005.Any solution that combines programs at runtime has to provide views that segregate them properly to maintain the programmer's segregated model. Java's bytecode support for multiple source files enables any debugger to step through a properly woven .class file in a source editor. However, some third-party decompilers are unable to process woven code because they expect code produced by Javac rather than all supported bytecode forms (see also "Problems", below).
Another alternative is
deploy-time weaving [http://www.forum2.org/tal/AspectJ2EE.pdf] . This basically implies post-processing, but rather than patching the generated code, this weaving approach "subclasses" existing classes so that the modifications are introduced by method-overriding. The existing classes remain untouched, even at runtime, and all existing tools (debuggers, profilers, etc.) can be used during development. A similar approach has already proven itself in the implementation of manyJava EE application servers, such asIBM 'sWebSphere .Terminology
The following are some standard terminology used in Aspect-oriented programming:
* Cross-cutting concerns: Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though the primary functionality of each class is very different, the code needed to perform the secondary functionality is often identical.
* Advice: This is the additional code that you want to apply to your existing model. In our example, this is the logging code that we want to apply whenever the thread enters or exits a method.
* Pointcut: This is the term given to the point of execution in the application at which cross-cutting concern needs to be applied. In our example, a pointcut is reached when the thread enters a method, and another pointcut is reached when the thread exits the method.
* Aspect: The combination of the pointcut and the advice is termed an aspect. In the example below, we add a logging aspect to our application by defining a pointcut and giving the correct advice.Comparison to other programming paradigms
Aspects emerged out of
object-oriented programming and computational reflection. AOP languages have functionality similar to, but more restricted than metaobject protocols. Aspects relate closely to programming concepts like subjects,mixin s, and delegation. Other ways to use aspect-oriented programming paradigms includeComposition Filters and the hyperslices approach. Since at least the 1970s, developers have been using forms of interception and dispatch-patching that are similar to some of the implementation techniques for AOP, but these never had the semantics that the crosscutting specifications were written in one place.Designers have considered alternative ways to achieve separation of code, such as C#'s partial types, but such approaches lack a quantification mechanism that allows reaching several join points of the code with one declarative statement.
Adoption risks
As with all immature technologies, widespread adoption of AOP is hindered by a lack of tool support, and widespread education. Some argue that slowing down is appropriate due to AOP's inherent ability to create unpredictable and widespread errors in a system. Implementation issues of some AOP languages mean that something as simple as renaming a function can lead to an aspect no longer being applied leading to negative side effects.
Programmers need to be able to read code and understand what's happening in order to prevent errors1. While they have grown accustomed to ignoring the details of method dispatch or container-supplied behaviors, many are uncomfortable with the idea that an aspect can be injected later adding behavior to their code. There are also valid security questions that code weaving raises.
Some programmers therefore object to all forms of bytecode weaving. AOP implementations are a particular concern for them because of its prevalence. One response in Java is to sign and seal the .jar files and prevent environments from deploying weaving class loaders affecting their code, but in some cases the deployment environment is not under their control.
Even with proper education, understanding crosscutting concerns can be difficult without proper support for visualizing both static structure and the dynamic flow of a program. Visualizing crosscutting concerns is just beginning to be supported in IDEs, as is support for aspect code assist and refactoring.
Given the power of AOP, if a programmer makes a logical mistake in expressing crosscutting, it can lead to widespread program failure. Conversely, another programmer may change the join points in a program -- e.g., by renaming or moving methods -- in ways that were not anticipated by the aspect writer, with
unintended consequence s. One advantage of modularizing crosscutting concerns is enabling one programmer to affect the entire system easily; as a result, such problems present as a conflict over responsibility between two or more developers for a given failure. Open questions of legal liability in such cases may also influence some to reject bytecode weaving altogether. However, the solution for these problems can be much easier in the presence of AOP, since only the aspect need be changed, whereas the corresponding problems without AOP can be quite difficult to fix.Bytecode decompilation and weaving has grown as an implementation method for many approaches including model-based programming. Early implementations of that technology can address only the subset of Java bytecode produced by Javac, the standard compiler, and thus fail when encountering valid bytecode produced by weavers that would never be produced by Javac. These problems can take some time to sort out since there are few developers familiar with bytecode internals. In the meantime, programming teams might have to choose between two incompatible development technologies.
Using AOP judiciously to develop your own code can result in powerful succinct expressiveness. Using AOP to add to code written by someone else (especially when you don't have the source code) is risky. Since the risk is to code written by others, code weaving can be emotional for the authors of the original code. There is little moral grounding to guide programmers in these matters because morality isn't something often applied to coding practices. Until these matters are sorted out, widespread adoption of AOP is itself at risk.
Usage of supporting methodologies such as
test-driven development ortest automation can reduce some of the risks associated with employing AOP. Assurance that the aspect doesn't negatively impact the original author's intent can be verified through running tests. Employing AOP without such a safety net is frightening to many programmers, especially those who are not familiar with the methodologies employed by responsible practitioners of AOP.The potential of AOP for creating
malware should also be considered. If security is a cross cutting concern implemented through the application of AOP techniques, then it is equally possible that breaking security can be implemented through injecting additional code at an appropriate place. For example, consider the impact of injecting code to return true at the beginning of a password verification function that returns a boolean value. This means that all programmers using languages that can be subjected to AOP techniques need to be aware of the potential of AOP to compromise their systems.Implementations
* For C#/VB.NET:
** [https://www.academicresourcecenter.net/curriculum/pfv.aspx?ID=6801 Aspect.NET]
** [http://www.rapier-loom.net LOOM.NET]
** [http://www.codeplex.com/entlib Enterprise Library 3.0 Policy Injection Application Block]
** [http://www.puzzleframework.com/forum/forum.aspx?Forum=24 Puzzle.NAspect]
** [http://sourceforge.net/projects/aspectdng/ AspectDNG]
** [http://www.castleproject.org/aspectsharp/ Aspect#]
** [http://theagiledeveloper.com/articles/Encase.aspx Encase]
** [http://composestar.sourceforge.net/ Compose*]
** [http://www.postsharp.org/ PostSharp] (see also their Wiki about [http://www.postsharp.org/aop.net AOP techniques on .NET] )
** [http://www.seasar.org/en/dotnet/ Seasar.NET]
** [http://dotspect.tigris.org/ DotSpect (.SPECT)]
** [http://www.springframework.net/ The Spring.NET Framework] as part of its functionality
** [http://www.cs.columbia.edu/~eaddy/wicca Wicca and Phx.Morph]
** [http://janus.cs.utwente.nl:8000/twiki/bin/view/AOSDNET/CharacterizationOfExistingApproaches An exhaustive analysis] onAOSD solutions for .NET is available from Twente University* For Java:
**AspectJ ( [http://eclipse.org/aspectj/] )
** [http://aspectwerkz.codehaus.org/ AspectWerkz (Now merged with AspectJ)]
** [http://www.azuki-framework.org/ Azuki]
** [http://www.caesarj.org CaesarJ]
** [http://composestar.sourceforge.net/ Compose*]
** [http://dynaop.dev.java.net/ Dynaop]
** [http://jac.objectweb.org JAC]
** [http://code.google.com/p/google-guice/ Guice] as part of its functionality
** Jakarta Hivemind
** [http://www.csg.is.titech.ac.jp/~chiba/javassist/ Javassist Home Page]
** [http://ssel.vub.ac.be/jasco/ JAsCo (and AWED)]
** [http://www.ics.uci.edu/~trungcn/jaml/ JAML]
** [http://labs.jboss.com/portal/jbossaop JBoss AOP]
** [http://roots.iai.uni-bonn.de/research/logicaj LogicAJ]
** [http://www.objectteams.org/ Object Teams]
** [http://prose.ethz.ch/ PROSE]
** [http://www.aspectbench.org/ The AspectBench Compiler for AspectJ (abc)]
** The Spring Framework as part of its functionality
**Seasar
** [http://roots.iai.uni-bonn.de/research/jmangler/ The JMangler Project]
** [http://injectj.sourceforge.net/ InjectJ]
** [http://www.csg.is.titech.ac.jp/projects/gluonj/ GluonJ]
** [http://www.st.informatik.tu-darmstadt.de/static/pages/projects/AORTA/Steamloom.jsp Steamloom]* For Flash ActionScript 2.0
** [http://www.as2lib.org/ as2lib]* For C/
C++ :
**AspectC++ ( [http://www.aspectc.org/] )
** [http://www.pnp-software.com/XWeaver/index.html XWeaver project]
** [http://wwwiti.cs.uni-magdeburg.de/iti_db/forschung/fop/featurec/ FeatureC++]
** [http://www.cs.ubc.ca/labs/spl/projects/aspectc.html AspectC]
** [http://www.aspectc.net AspeCt-oriented C]
** [http://users.ugent.be/~badams/aspicere2/ Aspicere2]* For
Cobol :
** [http://users.ugent.be/~kdschutt/cobble/ Cobble]* For Cocoa:
** [http://www.ood.neu.edu/aspectcocoa/ AspectCocoa]
* ForColdFusion :
** [http://www.coldspringframework.org ColdSpring]* For
Common Lisp :
** [http://common-lisp.net/project/closer/aspectl.html AspectL]* For Delphi:
** [http://code.google.com/p/infra/ InfraAspect]* For
JavaScript :
** [http://code.google.com/p/ajaxpect/ Ajaxpect]
** [http://www.jroller.com/page/deep?entry=aop_fun_with_javascript AOP Fun with JavaScript] (Replaced by Ajaxpect)
** [http://plugins.jquery.com/project/AOP jQuery AOP Plugin]
** [http://dojotoolkit.org Dojo Toolkit]
** [http://aspectes.tigris.org/ Aspectes]
** [http://www.aspectjs.com/ AspectJS]
** [http://humax.sourceforge.net Humax Web Framework]
** [http://www.cerny-online.com/cerny.js/ Cerny.js]
** [http://i.gotfresh.info/2007/12/7/advised-methods-for-javascript-with-prototype/ Advisable]* For Koala:
** AspectKoala* For
Common Lisp :
** [http://common-lisp.net/project/aspectl/ AspectL]* For Lua:
** [http://luaforge.net/projects/aspectlua/ AspectLua]* For make:
** [http://users.ugent.be/~badams/makao/ MAKAO]* For ML:
** [http://www.cs.princeton.edu/sip/projects/aspectml/ AspectML]* For
Perl :
** [http://search.cpan.org/perldoc?Aspect The Aspect Module]* For
PHP :
** [http://phpaspect.org PHPaspect]
** [http://www.aophp.net/ Aspect-Oriented PHP]
** [http://www.seasar.org/en/php5/index.html Seasar.PHP]
** [http://www.phpclasses.org/browse/package/2633.html AOP API for PHP] -PHPClasses Repository
** [http://www.phpclasses.org/browse/package/3215.html Transparent PHP AOP] -PHPClasses Repository
** [http://php-aop.googlecode.com PHP-AOP]* For Python:
** [http://aspyct.sourceforge.net/ Aspyct AOP]
** [http://www.cs.tut.fi/~ask/aspects/aspects.html Lightweight Python AOP]
** [http://www.logilab.org/projects/aspects Logilab's aspect module]
** [http://zope.org/Members/pje/Wikis/TransWarp/AOPTutorial/HomePage Python/Transwarp AOP Tutorial] (Replaced by PEAK)
** [http://peak.telecommunity.com/ PEAK]
** [http://pythius.sourceforge.net/ Pythius]
** [http://springpython.webfactional.com/wiki/AspectOrientedProgramming Spring Python's AOP module]
** [http://codespeak.net/pypy/dist/pypy/doc/aspect_oriented_programming.html Experimental aspect programming for PyPy]* For Ruby:
** [http://aspectr.sourceforge.net/ AspectR]
** [http://aquarium.rubyforge.org/ Aquarium]* For
Squeak Smalltalk
** [http://www.prakinf.tu-ilmenau.de/~hirsch/Projects/Squeak/AspectS/ AspectS]
** [http://csl.ensm-douai.fr/MetaclassTalk MetaclassTalk]* For
XML :
** [http://www.aspectXML.org AspectXML]* For
UML 2.0 :
** [http://www.iit.edu/~concur/weavr WEAVR]* For More Info (real-world implementations):
** [http://www.aosd.net AOSD.net ]ee also
*
Aspect-Oriented Software Development
*Programming paradigm s
*Stability Model
*Subject-oriented programming an alternative to Aspect-oriented programming
*Executable UML
*COMEFROM
*Decorator pattern
*Domain-driven design Publications
*cite book
first = Gregor
last = Kiczales
coauthors = John Lamping, Anurag Mendhekar, Chris Maeda, Cristina Lopes, Jean-Marc Loingtier, and John Irwin
year = 1997
title = Proceedings of the European Conference on Object-Oriented Programming, vol.1241
chapter = [http://citeseer.ist.psu.edu/kiczales97aspectoriented.html Aspect-Oriented Programming]
pages = pp.220–242 The paper originating AOP.
*cite book
first = Robert E.
last = Filman
authorlink = Robert E. Filman
coauthors =Tzilla Elrad ,Siobhàn Clarke , andMehmet Aksit
year =
title = Aspect-Oriented Software Development
id = ISBN 0-321-21976-7
*cite book
first = Renaud
last = Pawlak
authorlink = Renaud Pawlak
coauthors =Lionel Seinturier , andJean-Philippe Retaillé
year =
title = Foundations of AOP for J2EE Development
id = ISBN 1-59059-507-6
*cite book
first = Ramnivas
last = Laddad
authorlink = Ramnivas Laddad
year =
title = AspectJ in Action: Practical Aspect-Oriented Programming
id = ISBN 1-930110-93-6
*cite book
first = Ivar
last = Jacobson
authorlink = Ivar Jacobson
coauthors = andPan-Wei Ng
year =
title = Aspect-Oriented Software Development with Use Cases
id = ISBN 0-321-26888-1
* [http://www.cmsdevelopment.com/en/articles/aosdinphp/ Aspect-oriented Software Development and PHP, Dmitry Sheiko, 2006]
*cite book
first = Siobhán
last = Clarke
authorlink = Siobhán Clarke
coauthors = andElisa Baniassad
year = 2005
title = Aspect-Oriented Analysis and Design: The Theme Approach
id = ISBN 0-321-24674-8References
#
Edsger Dijkstra , [http://www.cs.utexas.edu/users/EWD/ewd02xx/EWD249.PDF "Notes on Structured Programming"] , pg. 1-2Notes
External links
* [http://aosd.net/conference Aspect-Oriented Software Development] (annual conference about AOP)
* [http://aosd.net/wiki AOSD Wiki] (Wiki specifically devoted to AOP)
* [http://www.eclipse.org/aspectj/doc/released/progguide/index.html AspectJ Programming Guide]
* [http://www.aspectbench.org/ The AspectBench Compiler for AspectJ] (another Java implementation)
* [http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=AOP@work: Series of IBM developerWorks articles on AOP]
* [http://www.aopworld.com AOPWorld.com] (Source of information on AOP and its related technologies)
* [http://www.javaworld.com/javaworld/jw-01-2002/jw-0118-aspect.html A detailed series of articles about the basics of aspect-oriented programming and AspectJ]
* [http://www.codefez.com/Home/tabid/36/articleType/ArticleView/articleId/98/AspectOrientedProgrammingwithTacobymarchoffman.aspx Introduction to Aspect Oriented Programming with RemObjects Taco]
* [http://www.cis.uab.edu/gray/Research/C-SAW/ Constraint-Specification Aspect Weaver]
* [http://www.devx.com/Java/Article/28422 Aspect- vs. Object-Oriented Programming: Which Technique, When?]
* [http://video.google.com/videoplay?docid=8566923311315412414&q=engEDU Gregor Kiczales, Professor of Computer Science, explaining AOP] (57min, video)
* [http://database.ittoolbox.com/documents/academic-articles/what-does-aspectoriented-programming-mean-to-cobol-4570 Aspect Oriented Programming in COBOL]
* [http://static.springframework.org/spring/docs/2.0.x/reference/aop.html Aspect Oriented Programming in Java with Spring Framework]
* [http://www.postsharp.org/aop.net A Wiki dedicated to AOP techniques on .NET]
* [http://www.forrester.com/Research/Document/Excerpt/0,7211,36794,00.html AOP considered harmful (Forrester)]
* [http://dssg.cs.umb.edu/wiki/index.php/Early_Aspects_for_Business_Process_Modeling Early Aspects for Business Process Modeling (An Aspect Oriented Language for BPMN)]
* [http://www.cs.bilkent.edu.tr/~bedir/CS586-AOSD AOSD Graduate Course at Bilkent University]
Wikimedia Foundation. 2010.