In computing, aspect-oriented programming (AOP) is a programming
paradigm that aims to increase modularity by allowing the separation
of cross-cutting concerns. It does so by adding additional behavior to
existing code (an advice) without modifying the code itself, instead
separately specifying which code is modified via a "pointcut"
specification, such as "log all function calls when the function's
name begins with 'set'". This allows behaviors that are not central to
the business logic (such as logging) to be added to a program without
cluttering the code, core to the functionality. AOP forms a basis for
aspect-oriented software development.
AOP includes programming methods 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
2 Motivation and basic concepts
3.1 AspectJ's join-point model 3.2 Other potential join point models 3.3 Inter-type declarations
5 Comparison to other programming paradigms 6 Adoption issues 7 Criticism 8 Implementations 9 See also 10 Notes and references 11 Further reading 12 External links
AOP has several direct antecedents A1 and A2: reflection and
metaobject protocols, subject-oriented programming, Composition
Filters and Adaptive Programming.
void transfer(Account fromAcc, Account toAcc, int amount) throws Exception if (fromAcc.getBalance() < amount) throw new InsufficientFundsException();
However, this transfer method overlooks certain considerations that a deployed application would require: it lacks security checks to verify that the current user has the authorization to perform this operation; a database transaction should encapsulate the operation in order to prevent accidental data loss; for diagnostics, the operation should be logged to the system log, etc. A version with all those new concerns, for the sake of example, could look somewhat like this:
void transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger, Database database) throws Exception logger.info("Transferring money...");
if (!isUserAuthorised(user, fromAcc)) logger.info("User has no permission."); throw new UnauthorisedUserException();
if (fromAcc.getBalance() < amount) logger.info("Insufficient funds."); throw new InsufficientFundsException();
database.commitChanges(); // Atomic operation.
In this 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. Now 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. 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) when one can access a bank account, 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 example above implementing logging in an aspect:
aspect Logger void Bank.transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger) logger.info("Transferring money...");
void Bank.getMoneyBack(User user, int transactionId, Logger logger) logger.info("User requested money back.");
// Other crosscutting code.
One can think of AOP 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) or do not want to change the function
in production code (debugging).
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 (for example,
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 Main article: AspectJ
The join points in
"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:
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 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:
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" and this is an instance of type Point in the com.company package. It can be referred to using the name "set()".
Advice specifies to run at (before, after, or around) a join point (specified with a pointcut) certain code (specified like code in a method). The AOP runtime invokes Advice automatically when the pointcut matches the join point. For example:
after() : set() Display.update();
This effectively specifies: "if the set() pointcut matches the join point, run the code Display.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 and extension methods, 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 a programmer implemented the crosscutting display-update concern using visitors instead, an inter-type declaration using the visitor pattern might 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 the Point 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 AOP programs can affect other programs in two different ways, depending on the underlying languages and environments:
a combined program is produced, valid in the original language and indistinguishable from an ordinary program to the ultimate interpreter 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 - a 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 methods, 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
Systems can implement source-level weaving 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.
Main article: Cross-cutting concern 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. Further concerns can be related to security such as access control  or information flow control. Even though each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical. Advice
Main article: Advice (programming) 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
Main article: 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
Main article: Aspect (computer science) The combination of the pointcut and the advice is termed an aspect. In the example above, we add a logging aspect to our application by defining a pointcut and giving the correct advice.
Comparison to other programming paradigms
Aspects emerged from 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 resemble some of the implementation methods for AOP, but these
never had the semantics that the crosscutting specifications provide
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.
Though it may seem unrelated, in testing, the use of mocks or stubs
requires the use of AOP techniques, like around advice, and so forth.
Here the collaborating objects are for the purpose of the test, a
cross cutting concern. Thus the various Mock Object frameworks provide
these features. For example, a process invokes a service to get a
balance amount. In the test of the process, where the amount comes
from is unimportant, only that the process uses the balance according
to the requirements.
Programmers need to be able to read code and understand what is
happening in order to prevent errors. 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. Beginning in 2002,
5 input x 10 print 'result is :' 15 print x
20 come from 10 25 x = x * x 30 return
with an AOP fragment with analogous semantics:
main() input x print(result(x))
input result(int x) return x around(int x): call(result(int)) && args(x) int temp = proceed(x) // return temp * temp
Indeed, the pointcut may depend on runtime condition and thus not be statically deterministic. This can be mitigated but not solved by static analysis and IDE support showing which advices potentially match. General criticisms are that AOP purports to improve "both modularity and the structure of code", but some counter that it instead undermines these goals and impedes "independent development and understandability of programs". Specifically, quantification by pointcuts breaks modularity: "one must, in general, have whole-program knowledge to reason about the dynamic execution of an aspect-oriented program." Further, while its goals (modularizing cross-cutting concerns) are well understood, its actual definition is unclear and not clearly distinguished from other well-established techniques. Cross-cutting concerns potentially cross-cut each other, requiring some resolution mechanism, such as ordering. Indeed, aspects can apply to themselves, leading to problems such as the liar paradox. Technical criticisms include that the quantification of pointcuts (defining where advices are executed) is "extremely sensitive to changes in the program", which is known as the fragile pointcut problem. The problems with pointcuts are deemed intractable: if one replaces the quantification of pointcuts with explicit annotations, one obtains attribute-oriented programming instead, which is simply an explicit subroutine call and suffers the identical problem of scattering that AOP was designed to solve. Implementations The following programming languages have implemented AOP, within the language, or as an external library:
PostSharp is a commercial AOP implementation with a free but limited edition. Unity, It provides an API to facilitate proven practices in core areas of programming including data access, security, logging, exception handling and others.
ActionScript Ada AutoHotkey C / C++ COBOL The Cocoa Objective-C frameworks ColdFusion Common Lisp Delphi Delphi Prism e (IEEE 1647) Emacs Lisp Groovy Haskell Java
Aspect-oriented software development Distributed AOP Attribute grammar, a formalism that can be used for aspect-oriented programming on top of functional programming languages Programming paradigms Subject-oriented programming, an alternative to Aspect-oriented programming Role-oriented programming, an alternative to Aspect-oriented programming Predicate dispatch, an older alternative to Aspect-oriented programming Executable UML Decorator pattern Domain-driven design
Notes and references
^ Kiczales, G.; Lamping, J.; Mendhekar, A.; Maeda, C.; Lopes, C.;
Loingtier, J. M.; Irwin, J. (1997).
Kiczales, G.; Lamping, J.; Mendhekar, A.; Maeda, C.; Lopes, C.;
Loingtier, J. M.; Irwin, J. (1997).
Eric Bodden's list of AOP tools in .net framework
Programming Styles: Procedural, OOP, and AOP
Programming Forum: Procedural, OOP, and AOP
Aspect-Oriented Software Development, annual conference on AOP
AOSD Wiki, Wiki on aspect-oriented software development
v t e
Aspect-oriented software development
Advice Aspect Aspect-oriented programming Aspect weaver Cross-cutting concerns Join point Pointcut
AspectC++ AspectJ AspectWerkz
LCCN: sh2005004988 GND: 4724728-9 BNF: cb1454