Aspect-oriented programming
In computing, aspect-oriented programming 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 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 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 discipline.
Aspect-oriented programming entails breaking down program logic into distinct parts. Nearly all programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing abstractions that can be used for implementing, abstracting and composing these concerns. Some concerns "cut across" multiple abstractions in a program, and defy these forms of implementation. These concerns are called cross-cutting concerns or horizontal concerns.
Logging exemplifies a crosscutting concern because a logging strategy necessarily affects every 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 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 by applying advice at various join points specified in a quantification or query called a pointcut. An aspect can also make binary-compatible structural changes to other classes, like adding members or parents.
History
AOP has several direct antecedents A1 and A2: reflection and metaobject protocols, subject-oriented programming, Composition Filters and Adaptive Programming.Gregor Kiczales and colleagues at Xerox PARC developed the explicit concept of AOP, and followed this with the AspectJ AOP extension to Java. IBM's research team pursued a tool approach over a language design approach and in 2001 proposed Hyper/J and the Concern Manipulation Environment, which have not seen wide usage.
The examples in this article use AspectJ.
The Microsoft Transaction Server is considered to be the first major application of AOP followed by Enterprise JavaBeans.
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 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 become 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:
void transfer throws Exception
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 throws Exception
In this example other interests have become tangled with the basic functionality. Transactions, security, and logging all exemplify cross-cutting concerns.
Now consider what happens if we suddenly need to change 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 and inter-type declarations. For example, a security module can include advice that performs a security check before accessing a bank account. The pointcut defines the times 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
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 or do not want to change the function in production code.
Join point models
The advice-related component of an aspect-oriented language defines a join point model. 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 join points, called pointcuts. Pointcuts determine whether a given join point matches. Most useful pointcut languages use a syntax like the base language and allow reuse through naming and combination.
- A means of specifying code to run at a join point. AspectJ calls this advice, and can run it before, after, and around join points. Some implementations also support things like defining a method in an aspect on another class.
AspectJ's join-point model
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
aspect DisplayUpdate
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.
Systems can implement source-level weaving using preprocessors 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 cannot process woven code because they expect code produced by Javac rather than all supported bytecode forms.
Deploy-time weaving offers another approach. 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 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
Standard terminology used in Aspect-oriented programming may include:;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. 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: 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 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.
Adoption issues
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, AspectJ began to provide IDE plug-ins to support the visualizing of crosscutting concerns. Those features, as well as aspect code assist and refactoring are now common.
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 the aspect writer did not anticipate, with unforeseen 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 needs to be changed, whereas the corresponding problems without AOP can be much more spread out.
Criticism
The most basic criticism of the effect of AOP is that control flow is obscured, and that it is not only worse than the much-maligned GOTO, but is in fact closely analogous to the joke COME FROM statement. The obliviousness of application, which is fundamental to many definitions of AOP, means that the advice is not visible, in contrast to an explicit method call. For example, compare the COME FROM program: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 result
around: call && args
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 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 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:- .NET Framework languages
- * is a commercial AOP implementation with a free but limited edition.
- *Unity 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
- Emacs Lisp
- Groovy
- Haskell
- Java
- *AspectJ
- JavaScript
- Logtalk
- Lua
- make
- Matlab
- ML
- Perl
- PHP
- Prolog
- Python
- Racket
- Ruby
- Squeak Smalltalk
- UML 2.0
- XML