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 and encapsulation 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 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.
For example, consider a banking application with a conceptually very simple method for transferring an amount from one account to another:
void transfer(Account fromAccount, Account toAccount, int amount) {
if (fromAccount.getBalance() < amount) {
throw new InsufficientFundsException();
}
fromAccount.withdraw(amount);
toAccount.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 fromAccount, Account toAccount, int amount) throws Exception {
if (!getCurrentUser().canPerform(OP_TRANSFER)) {
throw new SecurityException();
}
if (amount < 0) {
throw new NegativeTransferException();
}
Transaction tx = database.newTransaction();
try {
if (fromAccount.getBalance() < amount) {
throw new InsufficientFundsException();
}
fromAccount.withdraw(amount);
toAccount.deposit(amount);
tx.commit();
systemLog.logOperation(OP_TRANSFER, fromAccount, toAccount, amount);
}
catch(Exception e) {
tx.rollback();
throw e;
}
}
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.
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.
execution(* set*(*))
set" and there is exactly one argument of any type."Dynamic" PCDs check runtime types and bind variables. For example
this(Point)
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.*)
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.*);
set" and this is an instance of type Point in the com.company package. It can be referred to using the name "set()".
after() : set() {
Display.update();
}:
set() pointcut matches the join point, run the code Display.update() after the join point completes."
aspect DisplayUpdate {
void Point.acceptVisitor(Visitor v) {
v.visit(this);
}
// other crosscutting code...
}
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.
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
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.
The following are some standard terminology used in Aspect-oriented programming:
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.
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 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. 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 or test 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.
)