In software engineering, the programming paradigms of aspect-oriented programming (AOP) and aspect-oriented software development (AOSD) attempt to aid programmers in the separation of concerns, specifically crosscutting concerns, as an advance in modularization. AOP does so using primarily language changes, while AOSD uses a combination of language, environment, and methodology.
Separation of concerns entails breaking down a program into distinct parts that overlap in functionality as little as possible. All programming methodologies—including procedural programming and object-oriented programming—support some separation and encapsulation of concerns (or any area of interest or focus) into single entities. For example, procedures, packages, classes, and methods all help programmers encapsulate concerns into single entities. But some concerns defy these forms of encapsulation. Software engineers call these crosscutting concerns, because they cut across many modules in a program.
Logging offers one 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.
Gregor Kiczales and his team at Xerox PARC originated the concept of AOP. This team also developed the first and most popular AOP language, 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 and Concern Manipulation Environment, which have not seen wide usage. The examples here and in most discussions of AOP use AspectJ, if only as a lingua franca for expressing crosscutting that is otherwise implemented.
Any AOP language has some crosscutting expressions that encapsulate the concern in one place. The difference between languages lies in the power, safety, and usability of the language. E.g., interceptors that specify the methods to intercept express a limited form a 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.
Many AOP languages support method executions and field references as join points. In them the developer can write a pointcut to match, for example, all field-set operations on specific fields, and code to run when the field is actually set. Some also support things like defining a method in an aspect on another class. AOP languages can be compared based on the join points they expose, the language they use to specify the join points, the operations permitted at the join points, and the structural enhancements that can be expressed.
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); }
(the examples appear in a Java-like syntax, since at the time of writing, an overwhelming majority of AOP-related research and work takes place in Java or in Java-variants.)
However, in a real-world banking application, this transfer method seems far from adequate. 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) { if (!getCurrentUser().canPerform(OP_TRANSFER)) { throw new SecurityException(); } if (amount < 0) { throw new NegativeTransferException(); } if (fromAccount.getBalance() < amount) { throw new InsufficientFundsException(); } Transaction tx = database.newTransaction(); try { fromAccount.withdraw(amount); toAccount.deposit(amount); tx.commit(); systemLog.logOperation(OP_TRANSFER, fromAccount, toAccount, amount); } catch(Exception e) { tx.rollback(); } }
The code has lost its elegance and simplicity because the various new concerns 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 unlike the core concerns of the system, the cross-cutting concerns do not get properly encapsulated in their own modules. This increases the system complexity and makes maintenance 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.
execution(* set*(*) )
"Dynamic" PCD's 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" PCD's limit the lexical scope of the join point. For example
within(com.company.*)
Pointcuts can be composed and named for reuse. For example
pointcut set() : execution(* set*(*) ) && this(Point) && within(com.company.*);
Point in the com.company package. It can be referred to using the name "set()".
after() : set() {
Display.update();
}
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 than 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).
Cohen and Gil have produced a novel alternative: they present the notion of deploy-time weaving. This basically implies post-processing, but rather than patching the generated code, they suggest subclassing 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 J2EE application servers, such as IBM's WebSphere.
Designers have considered alternative ways to achieve separation of code, such as C#'s partial types. However, such approaches lack a quantification mechanism enabling programmers to reach several join points of the code with one declarative statement.
Understanding crosscutting concerns can be difficult without proper support for visualizing both static structure and the dynamic flow of a program. Concerns with debugging have largely been solved through debugger's adherence to Sun's standards for specifying source files. Visualizing crosscutting concerns is just beginning to be supported in IDE's, as is support for aspect code assist and refactoring.
Given the power of AOP, if a programmer makes a legal 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, which exacerbates the issue. In any case, the solution for these problems is 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.
Aspektově orientované programování | Aspektorientierte Programmierung | Programación Orientada a Aspectos | Programmation orientée aspect | Programmazione orientata agli aspetti | Aspectgeoriënteerd programmeren | アスペクト指向プログラミング | Programowanie aspektowe | Programação orientada a aspecto | Аспектно-ориентированная разработка программного обеспечения | 面向侧面的程序设计
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Aspect-oriented programming".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world