Aspect-oriented programming
In computing, aspect-oriented programming (AOP) is a programming paradigm in which secondary or supporting functions are isolated from the main program's business logic. It aims to increase modularity by allowing the separation of cross-cutting concerns, forming a basis for aspect-oriented software development.
AOP includes programming techniques and tools that support the modularization of concerns at the level of the source code, while aspect-oriented software development refers to a whole engineering discipline.
Contents |
Overview
Aspect-oriented programming entails breaking down a program into distinct parts (so-called concerns, cohesive areas of functionality). All programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing abstractions (e.g. procedures, modules, classes, methods) that can be used for implementing, abstracting and composing these concerns. But some concerns defy these forms of implementation and are called crosscutting concerns because they "cut across" multiple abstractions in a program.
Logging is a common 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 various join points (points in a program) specified in a quantification or query called a pointcut (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
AOP as such has a number of antecedents: the Visitor Design Pattern, CLOS MOP, and others[1]. AspectJ (perhaps the most popular general-purpose AOP package) was created by Gregor Kiczales and colleagues at Xerox PARC and made available in 2001. 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) Hyper/J and Concern Manipulation Environment, which have not seen wide usage. EmacsLisp changelog added AOP related code in version 19.28. The examples in this article use AspectJ as it is the most widely known of AOP languages.
Motivation and basic concepts
Typically, an aspect is scattered or tangled as code, making it harder to understand and maintain. It is scattered by virtue of the function (e.g. logging) being spread over a number of unrelated functions that might use its function, possibly in entirely unrelated systems, different source languages, etc. That means to change logging can require modifying all affected modules. Aspects are tangled not only with the mainline function of the systems in which they are expressed but also with each other. That means changing one concern entails understanding all the tangled concerns or having some means by which the effect of changes can be inferred.
For example, consider a banking application with a conceptually very simple method for transferring an amount from one account to another:[2]
void transfer(Account fromAcc, Account toAcc, int amount) throws Exception { if (fromAcc.getBalance() < amount) { throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); }
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:
void transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger) throws Exception { logger.info("tranfering money..."); if (! checkUserPermission(user)){ logger.info("User have no permission."); throw new UnauthorizeUserException(); } if (fromAcc.getBalance() < amount) { logger.info("Insufficient Funds, sorry :( "); throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); //get database connection //save transactions logger.info("Successful transaction. :) "); }
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 points) 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.
So for the above example if you would implement Logging in an Aspect.
aspect Logger { void Bank.transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger) { logger.info(“tranfering money...”); } void Bank.getMoneyBack(User user, int transactionId, Logger logger) { logger.info(“User requested money back”); } // other crosscutting code... }
AOP can be thought of as a debugging tool or as a user level tool. Advice should be reserved for the cases where you cannot get the function changed (user level) (from Emacs Documentation) or do not want to change the function in production code (debugging).
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 points 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 pointcuts. 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 for AspectJ) and allow reuse through naming and combination.
- A means of specifying code to run at a join point. In AspectJ, 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 classes, 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 the visitor pattern would look like this in AspectJ:
aspect DisplayUpdate { void Point.acceptVisitor(Visitor v) { v.visit(this); } // other crosscutting code... }
- 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 known as weaving, which is special case of program transformation. An aspect weaver reads the aspect-oriented code and generates appropriate object-oriented code with the aspects integrated. 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 of AspectWerkz 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.[3] 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 many Java EE application servers, such as IBM's WebSphere.
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, mixins, and delegation. Other ways to use aspect-oriented programming paradigms include Composition 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 issues
Programmers need to be able to read code and understand what is happening in order to prevent errors.[4] 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 consequences. 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. 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 much more spread out.
Implementations
AOP has been implemented (in either the language itself or as external library) for the following programming languages:
- AutoHotkey[5]
- .NET Framework languages (C# / VB.NET)[6]
- C / C++[7]
- Cobol[8]
- Cocoa[9]
- ColdFusion[10]
- Common Lisp[11]
- Delphi[12][13]
- Delphi Prism [14]
- e (IEEE 1647)
- Haskell[15]
- Java[16]
- JavaScript[17]
- Emacs Lisp[18]
- Lua[19]
- make[20]
- ML[21]
- Perl[22]
- PHP[23]
- Prolog[24]
- Python[25]
- Ruby[26][27][28]
- Squeak Smalltalk[29][30]
- UML 2.0[31]
- XML[32]
See also
- Aspect-Oriented Software Development
- Programming paradigms
- Stability Model
- Subject-oriented programming an alternative to Aspect-oriented programming
- Executable UML
- COMEFROM
- Decorator pattern
- Domain-driven design
Notes and references
- ^ "Adaptive Object Oriented Programming: The Demeter Approach with Propagtion Patterns" Karl Liebherr 1996 ISBN 0-534-94602-X presents a well worked version of essentially the same thing (Lieberherr subsequently recognized this and reframed his approach).
- ^ Note: The examples in this article appear in a syntax that is similar to that of the Java programming language.
- ^ http://www.forum2.org/tal/AspectJ2EE.pdf
- ^ Edsger Dijkstra, Notes on Structured Programming, pg. 1-2
- ^ Function Hooks
- ^ Numerous: LOOM.NET, Enterprise Library 3.0 Policy Injection Application Block, AspectDNG, Aspect#, Compose*, PostSharp, Seasar.NET, DotSpect (.SPECT), Spring.NET (as part of its functionality), Wicca and Phx.Morph, SetPoint
- ^ Several: AspectC++, XWeaver project, FeatureC++, AspectC, AspeCt-oriented C, Aspicere
- ^ Cobble
- ^ AspectCocoa
- ^ ColdSpring
- ^ AspectL
- ^ InfraAspect
- ^ MeAOP in MeSDK
- ^ RemObjects Cirrus
- ^ monad (functional programming),Monads As a theoretical basis for AOP, and Aspect-oriented programming with type classes.
- ^ Numerous others: CaesarJ, Compose*, Dynaop, JAC, Google Guice (as part of its functionality), Jakarta Hivemind, Javassist, JAsCo (and AWED), JAML, JBoss AOP, LogicAJ, Object Teams, PROSE, The AspectBench Compiler for AspectJ (abc), Spring framework (as part of its functionality), Seasar, The JMangler Project, InjectJ, GluonJ, Steamloom
- ^ Many: Advisable, Ajaxpect, jQuery AOP Plugin, Aspectes, AspectJS, Cerny.js, Dojo Toolkit, Humax Web Framework, Joose, Prototype - Prototype Function#wrap
- ^ Emacs Advice Functions
- ^ AspectLua
- ^ MAKAO
- ^ AspectML
- ^ The Aspect Module
- ^ Several: PHPaspect, Aspect-Oriented PHP, Seasar.PHP, PHP-AOP, FLOW3
- ^ "Whirl"
- ^ Several: PEAK, Aspyct AOP, Lightweight Python AOP, Logilab's aspect module, Pythius, Spring Python's AOP module
- ^ AspectR
- ^ AspectR-Fork
- ^ Aquarium
- ^ AspectS
- ^ MetaclassTalk
- ^ WEAVR
- ^ AspectXML
Further reading
- Kiczales, Gregor; John Lamping, Anurag Mendhekar, Chris Maeda, Cristina Lopes, Jean-Marc Loingtier, and John Irwin (1997). "Aspect-Oriented Programming". Proceedings of the European Conference on Object-Oriented Programming, vol.1241. pp. 220–242. The paper generally considered to be the authoritative reference for AOP.
- Filman, Robert E.; Tzilla Elrad, Siobhàn Clarke, and Mehmet Aksit. Aspect-Oriented Software Development. ISBN 0-321-21976-7.
- Pawlak, Renaud; Lionel Seinturier, and Jean-Philippe Retaillé. Foundations of AOP for J2EE Development. ISBN 1-59059-507-6.
- Laddad, Ramnivas. AspectJ in Action: Practical Aspect-Oriented Programming. ISBN 1-930110-93-6.
- Jacobson, Ivar; and Pan-Wei Ng. Aspect-Oriented Software Development with Use Cases. ISBN 0-321-26888-1.
- Aspect-oriented Software Development and PHP, Dmitry Sheiko, 2006
- Clarke, Siobhán; and Elisa Baniassad (2005). Aspect-Oriented Analysis and Design: The Theme Approach. ISBN 0-321-24674-8.
- Yedduladoddi, Raghu (2009). Aspect Oriented Software Development: An Approach to Composing UML Design Models. ISBN 3639120841.
- "Adaptive Object-Oriented Programming Using Graph-Based Customization" – Lieberherr, Silva-Lepe, et al. - 1994
External links
- Programming Styles: Procedural, OOP, and AOP
- Aspect-Oriented Software Development (annual conference about AOP)
- AOSD Wiki (Wiki specifically devoted to AOP)
- AspectJ Programming Guide
- The AspectBench Compiler for AspectJ (another Java implementation)
- Series of IBM developerWorks articles on AOP
- AOPWorld.com (Source of information on AOP and its related technologies)
- A detailed series of articles about the basics of aspect-oriented programming and AspectJ
- Introduction to Aspect Oriented Programming with RemObjects Taco
- Constraint-Specification Aspect Weaver
- Aspect- vs. Object-Oriented Programming: Which Technique, When?
- Gregor Kiczales, Professor of Computer Science, explaining AOP (57min, video)
- Aspect Oriented Programming in COBOL
- Aspect Oriented Programming in Java with Spring Framework
- A Wiki dedicated to AOP techniques on.NET
- AOP considered harmful (Forrester)
- Early Aspects for Business Process Modeling (An Aspect Oriented Language for BPMN)
- AOSD Graduate Course at Bilkent University
- Introduction to AOP - Software Engineering Radio Podcast Episode 106