Aspect-Oriented Programming
Wikipedia Notes
Aspect-oriented programming entails breaking down program logic into distinct parts (so-calledconcerns, cohesive areas of functionality). Nearly 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 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 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.
AspectJ
Simple language description[edit]
All valid Java programs are also valid AspectJ programs, but AspectJ lets programmers define special constructs called aspects. Aspects can contain several entities unavailable to standard classes. These are:
- inter-type declarations—allow a programmer to add methods, fields, or interfaces to existing classes from within the aspect. This example adds an
acceptVisitor
(see visitor pattern) method to thePoint
class:
aspect VisitAspect { void Point.acceptVisitor(Visitor v) { v.visit(this); } }
- pointcuts — allow a programmer to specify join points (well-defined moments in the execution of a program, like method call, object instantiation, or variable access). All pointcuts are expressions (quantifications) that determine whether a given join point matches. For example, this point-cut matches the execution of any instance method in an object of type
Point
whose name begins withset
:
pointcut set() : execution(* set*(..) ) && this(Point);
- advice — allows a programmer to specify code to run at a join point matched by a pointcut. The actions can be performed before, after, oraround the specified join point. Here, the advice refreshes the display every time something on
Point
is set, using the pointcut declared above:
after () : set() { Display.update(); }
AspectJ also supports limited forms of pointcut-based static checking and aspect reuse (by inheritance). See the AspectJ Programming Guide for a more detailed description of the language.
Motivation and basic concepts[edit]
Typically, an aspect is scattered or tangled as code, making it harder to understand and maintain. It is scattered by virtue of the function (such as 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 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:[5]
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 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) throws Exception { logger.info("Transferring money..."); if (! checkUserPermission(user)){ logger.info("User has no permission."); throw new UnauthorizedUserException(); } if (fromAcc.getBalance() < amount) { logger.info("Insufficient funds."); throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); //get database connection //save transactions logger.info("Successful transaction."); }
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 pointcutdefines 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 above example 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)[6] or do not want to change the function in production code (debugging).
Join point models[edit]
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 (for example, AspectJ uses Java signatures) 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.
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
- Join Points: 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 exclude loops, super calls, throws clauses, multiple statements, etc.
- Pointcuts: 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:
- Primitive PCDs
- Kinded PCDs
- Dynamic PCDs
- Scope PCDs
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 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 codeDisplay.update()
after the join point completes." Inter-type declarations[edit]
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 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 theacceptVisitor
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 (contract), unless the AOP implementation can expect to control all clients at all times.Terminology
Standard terminology used in Aspect-oriented programming may include:- Cross-cutting concerns (philosophy)
- 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 each class has a very different primary functionality, the code needed to perform the secondary functionality is often identical.
- Advice (additional code)
- 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 (position)
- 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.
pre-conditions, post-conditions. - Aspect (aspect = pointcut + advice)
- 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.
primitive pointcut designator:
ReplyDelete- call, execution - this, target
- get, set - within, withincode
- handler - cflow , cflowbelow
- initialization, staticinitialization
advice:
• before before proceeding at join point
• after returning a value to join point
• after throwing a throwable to join point
• after returning to join point either way
• around on arrival at join point gets explicit
control over when&if program proceeds