Getting Started with AspectJ Introduction Many software developers are attracted to the idea of aspect-oriented programming aspect-oriented programming (AOP) AOP aspect-oriented programming but unsure about how to begin using the technology. They recognize the concept of crosscutting concerns, and know that they have had problems with the implementation of such concerns in the past. But there are many questions about how to adopt AOP into the development process. Common questions include: Can I use aspects in my existing code? What kinds of benefits can I expect to get from using aspects? How do I find aspects in my programs? How steep is the learning curve for AOP? What are the risks of using this new technology? This chapter addresses these questions in the context of AspectJ a general-purpose aspect-oriented extension to Java. A series of abridged examples illustrate the kinds of aspects programmers may want to implement using AspectJ and the benefits associated with doing so. Readers who would like to understand the examples in more detail, or who want to learn how to program examples like these, can find the complete examples and supporting material on the AspectJ web site(). A significant risk in adopting any new technology is going too far too fast. Concern about this risk causes many organizations to be conservative about adopting new technology. To address this issue, the examples in this chapter are grouped into three broad categories, with aspects that are easier to adopt into existing development projects coming earlier in this chapter. The next section, , we present the core of AspectJ's semantics, and in , we present aspects that facilitate tasks such as debugging, testing and performance tuning of applications. And, in the section following, , we present aspects that implement crosscutting functionality common in Java applications. We will defer discussing a third category of aspects, reusable aspects until . These categories are informal, and this ordering is not the only way to adopt AspectJ. Some developers may want to use a production aspect right away. But our experience with current AspectJ users suggests that this is one ordering that allows developers to get experience with (and benefit from) AOP technology quickly, while also minimizing risk. AspectJ Semantics AspectJ semantics overview This section presents a brief introduction to the features of AspectJ used later in this chapter. These features are at the core of the language, but this is by no means a complete overview of AspectJ. The semantics are presented using a simple figure editor system. A Figure consists of a number of FigureElements, which can be either Points or Lines. The Figure class provides factory services. There is also a Display. Most example programs later in this chapter are based on this system as well. UML for the FigureEditor example The motivation for AspectJ (and likewise for aspect-oriented programming) is the realization that there are issues or concerns that are not well captured by traditional programming methodologies. Consider the problem of enforcing a security policy in some application. By its nature, security cuts across many of the natural units of modularity of the application. Moreover, the security policy must be uniformly applied to any additions as the application evolves. And the security policy that is being applied might itself evolve. Capturing concerns like a security policy in a disciplined way is difficult and error-prone in a traditional programming language. Concerns like security cut across the natural units of modularity. For object-oriented programming languages, the natural unit of modularity is the class. But in object-oriented programming languages, crosscutting concerns are not easily turned into classes precisely because they cut across classes, and so these aren't reusable, they can't be refined or inherited, they are spread through out the program in an undisciplined way, in short, they are difficult to work with. Aspect-oriented programming is a way of modularizing crosscutting concerns much like object-oriented programming is a way of modularizing common concerns. AspectJ is an implementation of aspect-oriented programming for Java. AspectJ adds to Java just one new concept, a join point, and a few new constructs: pointcuts, advice, introduction and aspects. Pointcuts and advice dynamically affect program flow, and introduction statically affects a program's class heirarchy. A join point join point is a well-defined point in the program flow. Pointcuts pointcut select certain join points and values at those points. Advice advice defines code that is executed when a pointcut is reached. These are, then, the dynamic parts of AspectJ. AspectJ also has a way of affecting a program statically. Introduction introduction is how AspectJ modifies a program's static structure, namely, the members of its classes and the relationship between classes. The last new construct in AspectJ is the aspect. aspect Aspects, are AspectJ's unit of modularity for crosscutting concerns They are defined in terms of pointcuts, advice and introduction. In the sections immediately following, we are first going to look at join points and how they compose into pointcuts. Then we will look at advice, the code which is run when a pointcut is reached. We will see how to combine pointcuts and advice into aspects, AspectJ's reusable, inheritable unit of modularity. Lastly, we will look at how to modify a program's class structure with introduction. The Dynamic Join Point Model join point model A critical element in the design of any aspect-oriented language is the join point model. The join point model provides the common frame of reference that makes it possible to define the dynamic structure of crosscutting concerns. This chapter describes AspectJ's dynamic join points, in which join points are certain well-defined points in the execution of the program. Later we will discuss introduction, AspectJ's form for modifying a program statically. AspectJ provides for many kinds of join points, but this chapter discusses only one of them: method call join points. A method call join point encompasses the actions of an object receiving a method call. It includes all the actions that comprise a method call, starting after all arguments are evaluated up to and including normal or abrupt return. Each method call itself is one join point. The dynamic context of a method call may include many other join points: all the join points that occur when executing the called method and any methods that it calls. Pointcut Designators In AspectJ, pointcut designators (or simply pointcuts) identify certain join points in the program flow. For example, the pointcut call(void Point.setX(int)) identifies any call to the method setX defined on Point objects. Pointcuts can be composed using a filter composition semantics, so for example: call(void Point.setX(int)) || call(void Point.setY(int)) identifies any call to either the setX or setY methods defined by Point. Programmers can define their own pointcuts, and pointcuts can identify join points from many different classes — in other words, they can crosscut classes. So, for example, the following declares a new, named pointcut: pointcut move(): call(void FigureElement.setXY(int,int)) || call(void Point.setX(int)) || call(void Point.setY(int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)); The effect of this declaration is that move is now a pointcut that identifies any call to methods that move figure elements. Property-Based Primitive Pointcuts pointcut primitive pointcut name-based pointcut property-based The previous pointcuts are all based on explicit enumeration of a set of method signatures. We call this name-based crosscutting. AspectJ also provides mechanisms that enable specifying a pointcut in terms of properties of methods other than their exact name. We call this property-based crosscutting. The simplest of these involve using wildcards in certain fields of the method signature. For example: call(void Figure.make*(..)) identifies calls to any method defined on Figure, for which the name begins with "make", specifically the factory methods makePoint and makeLine; and call(public * Figure.* (..)) identifies calls to any public method defined on Figure. One very powerful primitive pointcut, cflow, identifies join points based on whether they occur in the dynamic context of another pointcut. So cflow(move()) identifies all join points that occur between receiving method calls for the methods in move and returning from those calls (either normally or by throwing an exception.) Advice advice Pointcuts are used in the definition of advice. AspectJ has several different kinds of advice that define additional code that should run at join points. Before advice advice before runs when a join point is reached and before the computation proceeds, i.e. it runs when computation reaches the method call and before the actual method starts running. After advice advice after runs after the computation 'under the join point' finishes, i.e. after the method body has run, and just before control is returned to the caller. Around advice advice around runs when the join point is reached, and has explicit control over whether the computation under the join point is allowed to run at all. (Around advice and some variants of after advice are not discussed in this chapter.) Exposing Context in Pointcuts Pointcuts can also expose part of the execution context at their join points. Values exposed by a pointcut can be used in the body of advice declarations. In the following code, the pointcut exposes three values from calls to setXY: the FigureElement receiving the call, the new value for x and the new value for y. The advice then prints the figure element that was moved and its new x and y coordinates after each setXY method call. Introduction aspect Introduction is AspectJ's form for modifying classes and their hierarchy. Introduction adds new members to classes and alters the inheritance relationship between classes. Unlike advice that operates primarily dynamically, introduction operates statically, at compilation time. Introduction changes the declaration of classes, and it is these changed classes that are inherited, extended or instantiated by the rest of the program. Consider the problem of adding a new capability to some existing classes that are already part of a class heirarchy, i.e. they already extend a class. In Java, one creates an interface that captures this new capability, and then adds to each affected class a method that implements this interface. AspectJ can do better. The new capability is a crosscutting concern because it affects multiple classes. Using AspectJ's introduction form, we can introduce into existing classes the methods or fields that are necessary to implement the new capability. Suppose we want to have Screen objects observe changes to Point objects, where Point is an existing class. We can implement this by introducing into the class Point an instance field, observers, that keeps track of the Screen objects that are observing Points. Observers are added or removed with the static methods addObserver and removeObserver. The pointcut changes defines what we want to observe, and the after advice defines what we want to do when we observe a change. Note that neither Screen's nor Point's code has to be modified, and that all the changes needed to support this new capability are local to this aspect. Aspect Declarations An aspect aspect is a modular unit of crosscutting implementation. It is defined very much like a class, and can have methods, fields, and initializers. The crosscutting implementation is provided in terms of pointcuts, advice and introductions. Only aspects may include advice, so while AspectJ may define crosscutting effects, the declaration of those effects is localized. The next three sections present the use of aspects in increasingly sophisticated ways. Development aspects are easily removed from production builds. Production aspects are intended to be used in both development and in production, but tend to affect only a few classes. Finally, reusable aspects require the most experience to get right. Development Aspects aspect development This section presents examples of aspects that can be used during development of Java applications. These aspects facilitate debugging, testing and performance tuning work. The aspects define behavior that ranges from simple tracing, to profiling, to testing of internal consistency within the application. Using AspectJ makes it possible to cleanly modularize this kind of functionality, thereby making it possible to easily enable and disable the functionality when desired. Tracing, Logging, and Profiling tracing logging profiling This first example shows how to increase the visibility of the internal workings of a program. It is a simple tracing aspect that prints a message at specified method calls. In our figure editor example, one such aspect might simply trace whenever points are drawn. This code makes use of the thisJoinPoint special variable. Within all advice bodies this variable is bound to an object that describes the current join point. The effect of this code is to print a line like the following every time a figure element receives a draw method call: To understand the benefit of coding this with AspectJ consider changing the set of method calls that are traced. With AspectJ, this just requires editing the definition of the tracedCalls pointcut and recompiling. The individual methods that are traced do not need to be edited. When debugging, programmers often invest considerable effort in figuring out a good set of trace points to use when looking for a particular kind of problem. When debugging is complete or appears to be complete it is frustrating to have to lose that investment by deleting trace statements from the code. The alternative of just commenting them out makes the code look bad, and can cause trace statements for one kind of debugging to get confused with trace statements for another kind of debugging. With AspectJ it is easy to both preserve the work of designing a good set of trace points and disable the tracing when it isn t being used. This is done by writing an aspect specifically for that tracing mode, and removing that aspect from the compilation when it is not needed. This ability to concisely implement and reuse debugging configurations that have proven useful in the past is a direct result of AspectJ modularizing a crosscutting design element the set of methods that are appropriate to trace when looking for a given kind of information. Profiling and Logging logging profiling Our second example shows you how to do some very specific profiling. Although many sophisticated profiling tools are available, and these can gather a variety of information and display the results in useful ways, you may sometimes want to profile or log some very specific behavior. In these cases, it is often possible to write a simple aspect similar to the ones above to do the job. For example, the following aspect Since aspects are by default singleton aspects, i.e. there is only one instance of the aspect, fields in a singleton aspect are similar to static fields in class. will count the number of calls to the rotate method on a Line and the number of calls to the set* methods of a Point that happen within the control flow of those calls to rotate: Aspects have an advantage over standard profiling or logging tools because they can be programmed to ask very specific and complex questions like, "How many times is the rotate method defined on Line objects called, and how many times are methods defined on Point objects whose name begins with `set' called in fulfilling those rotate calls"? Pre- and Post-Conditions pre-condition post-condition assertion Many programmers use the "Design by Contract" style popularized by Bertand Meyer in Object-Oriented Software Construction, 2/e. In this style of programming, explicit pre-conditions test that callers of a method call it properly and explicit post-conditions test that methods properly do the work they are supposed to. AspectJ makes it possible to implement pre- and post-condition testing in modular form. For example, this code MAX_X ) throw new IllegalArgumentException("x is out of bounds."); } before(int y): setY(y) { if ( y < MIN_Y || y > MAX_Y ) throw new IllegalArgumentException("y is out of bounds."); } } ]]> implements the bounds checking aspect of pre-condition testing for operations that move points. Notice that the setX pointcut refers to all the operations that can set a point's x coordinate; this includes the setX method, as well as half of the setXY method. In this sense the setX pointcut can be seen as involving very fine-grained crosscutting—it names the the setX method and half of the setXY method. Even though pre- and post-condition testing aspects can often be used only during testing, in some cases developers may wish to include them in the production build as well. Again, because AspectJ makes it possible to modularize these crosscutting concerns cleanly, it gives developers good control over this decision. Contract Enforcement contract enforcement The property-based crosscutting mechanisms can be very useful in defining more sophisticated contract enforcement. One very powerful use of these mechanisms is to identify method calls that, in a correct program, should not exist. For example, the following aspect enforces the constraint that only the well-known factory methods can add an element to the registry of figure elements. Enforcing this constraint ensures that no figure element is added to the registry more than once. This aspect uses the withincode primitive pointcut to denote all join points that occur within the body of the factory methods on FigureElement (the methods with names that begin with "make"). This is a property-based pointcut because it identifies join points based not on their signature, but rather on the property that they occur specifically within the code of another method. The before advice declaration effectively says signal an error for any calls to register that are not within the factory methods. Configuration Management configuration management Configuration management for aspects can be handled using a variety of make-file like techniques. To work with optional aspects, the programmer can simply define their make files to either include the aspect in the call to the AspectJ compiler or not, as desired. Developers who want to be certain that no aspects are included in the production build can do so by configuring their make files so that they use a traditional Java compiler for production builds. To make it easy to write such make files, the AspectJ compiler has a command-line interface that is consistent with ordinary Java compilers. Production Aspects aspect production This section presents examples of aspects that are inherently intended to be included in the production builds of an application. Production aspects tend to add functionality to an application rather than merely adding more visibility of the internals of a program. Again, we begin with name-based aspects and follow with property-based aspects. Name-based production aspects tend to affect only a small number of methods. For this reason, they are a good next step for projects adopting AspectJ. But even though they tend to be small and simple, they can often have a significant effect in terms of making the program easier to understand and maintain. Change Monitoring change monitoring The first example production aspect shows how one might implement some simple functionality where it is problematic to try and do it explicitly. It supports the code that refreshes the display. The role of the aspect is to maintain a dirty bit indicating whether or not an object has moved since the last time the display was refreshed. Implementing this functionality as an aspect is straightforward. The testAndClear method is called by the display code to find out whether a figure element has moved recently. This method returns the current state of the dirty flag and resets it to false. The pointcut move captures all the method calls that can move a figure element. The after advice on move sets the dirty flag whenever an object moves. Even this simple example serves to illustrate some of the important benefits of using AspectJ in production code. Consider implementing this functionality with ordinary Java: there would likely be a helper class that contained the dirty flag, the testAndClear method, as well as a setFlag method. Each of the methods that could move a figure element would include a call to the setFlag method. Those calls, or rather the concept that those calls should happen at each move operation, are the crosscutting concern in this case. The AspectJ implementation has several advantages over the standard implementation: The structure of the crosscutting concern is captured explicitly. The moves pointcut clearly states all the methods involved, so the programmer reading the code sees not just individual calls to setFlag, but instead sees the real structure of the code. The IDE support included with AspectJ automatically reminds the programmer that this aspect advises each of the methods involved. The IDE support also provides commands to jump to the advice from the method and vice-versa. Evolution is easier. If, for example, the aspect needs to be revised to record not just that some figure element moved, but rather to record exactly which figure elements moved, the change would be entirely local to the aspect. The pointcut would be updated to expose the object being moved, and the advice would be updated to record that object. The paper An Overview of AspectJ, presented at ECOOP 2001, presents a detailed discussion of various ways this aspect could be expected to evolve.) The functionality is easy to plug in and out. Just as with development aspects, production aspects may need to be removed from the system, either because the functionality is no longer needed at all, or because it is not needed in certain configurations of a system. Because the functionality is modularized in a single aspect this is easy to do. The implementation is more stable. If, for example, the programmer adds a subclass of Line that overrides the existing methods, this advice in this aspect will still apply. In the ordinary Java implementation the programmer would have to remember to add the call to setFlag in the new overriding method. This benefit is often even more compelling for property-based aspects (see the section ). Context Passing The crosscutting structure of context passing can be a significant source of complexity in Java programs. Consider implementing functionality that would allow a client of the figure editor (a program client rather than a human) to set the color of any figure elements that are created. Typically this requires passing a color, or a color factory, from the client, down through the calls that lead to the figure element factory. All programmers are familiar with the inconvenience of adding a first argument to a number of methods just to pass this kind of context information. Using AspectJ, this kind of context passing can be implemented in a modular way. The following code adds after advice that runs only when the factory methods of Figure are called in the control flow of a method on a ColorControllingClient. This aspect affects only a small number of methods, but note that the non-AOP implementation of this functionality might require editing many more methods, specifically, all the methods in the control flow from the client to the factory. This is a benefit common to many property-based aspects while the aspect is short and affects only a modest number of benefits, the complexity the aspect saves is potentially much larger. Providing Consistent Behavior This example shows how a property-based aspect can be used to provide consistent handling of functionality across a large set of operations. This aspect ensures that all public methods of the com.xerox package log any errors (a kind of throwable, different from Exception) they throw to their caller. The publicMethodCall pointcut captures the public method calls of the package, and the after advice runs whenever one of those calls returns throwing an exception. The advice logs the exception and then the throw resumes. In some cases this aspect can log an exception twice. This happens if code inside the com.xerox package itself calls a public method of the package. In that case this code will log the error at both the outermost call into the com.xerox package and the re-entrant call. The cflow primitive pointcut can be used in a nice way to exclude these re-entrant calls: The following aspect is taken from work on the AspectJ compiler. The aspect advises about 35 methods in the JavaParser class. The individual methods handle each of the different kinds of elements that must be parsed. They have names like parseMethodDec, parseThrows, and parseExpr. This example exhibits a property found in many aspects with large property-based pointcuts. In addition to a general property based pattern call(* JavaParser.parse*(..)) it includes an exception to the pattern !call(Stmt parseVarDec(boolean)). The exclusion of parseVarDec happens because the parsing of variable declarations in Java is too complex to fit with the clean pattern of the other parse* methods. Even with the explicit exclusion this aspect is a clear expression of a clean crosscutting modularity. Namely that all parse* methods that return ASTObjects, except for parseVarDec share a common behavior for establishing the parse context of their result. The process of writing an aspect with a large property-based pointcut, and of developing the appropriate exceptions can clarify the structure of the system. This is especially true, as in this case, when refactoring existing code to use aspects. When we first looked at the code for this aspect, we were able to use the IDE support provided in AJDE for JBuilder to see what methods the aspect was advising compared to our manual coding. We quickly discovered that there were a dozen places where the aspect advice was in effect but we had not manually inserted the required functionality. Two of these were bugs in our prior non-AOP implementation of the parser. The other ten were needless performance optimizations. So, here, refactoring the code to express the crosscutting structure of the aspect explicitly made the code more concise and eliminated latent bugs. Static Crosscutting: Introduction introduction Up until now we have only seen constructs that allow us to implement dynamic crosscutting, crosscutting that changes the way a program executes. AspectJ also allows us to implement static crosscutting, crosscutting that affects the static structure of our progams. This is done using forms called introduction. An introduction is a member of an aspect, but it defines or modifies a member of another type (class). With introduction we can add methods to an existing class add fields to an existing class extend an existing class with another implement an interface in an existing class convert checked exceptions into unchecked exceptions Suppose we want to change the class Point to support cloning. By using introduction, we can add that capability. The class itself doesn't change, but its users (here the method main) may. In the example below, the aspect CloneablePoint does three things: declares that the class Point implements the interface Cloneable, declares that the methods in Point whose signature matches Object clone() should have their checked exceptions converted into unchecked exceptions, and adds a method that overrides the method clone in Point, which was inherited from Object. class Point { private int x, y; Point(int x, int y) { this.x = x; this.y = y; } int getX() { return this.x; } int getY() { return this.y; } void setX(int x) { this.x = x; } void setY(int y) { this.y = y; } public static void main(String[] args) { Point p = new Point(3,4); Point q = (Point) p.clone(); } } aspect CloneablePoint { declare parents: Point implements Cloneable; declare soft: CloneNotSupportedException: execution(Object clone()); Object Point.clone() { return super.clone(); } } Introduction is a powerful mechanism for capturing crosscutting concerns because it not only changes the behavior of components in an application, but also changes their relationship. Conclusion AspectJ is a simple and practical aspect-oriented extension to Java. With just a few new constructs, AspectJ provides support for modular implementation of a range of crosscutting concerns. Adoption of AspectJ into an existing Java development project can be a straightforward and incremental task. One path is to begin by using only development aspects, going on to using production aspects and then reusable aspects after building up experience with AspectJ. Adoption can follow other paths as well. For example, some developers will benefit from using production aspects right away. Others may be able to write clean reusable aspects almost right away. AspectJ enables both name-based and property based crosscutting. Aspects that use name-based crosscutting tend to affect a small number of other classes. But despite their small scale, they can often eliminate significant complexity compared to an ordinary Java implementation. Aspects that use property-based crosscutting can have small or large scale. Using AspectJ results in clean well-modularized implementations of crosscutting concerns. When written as an AspectJ aspect the structure of a crosscutting concern is explicit and easy to understand. Aspects are also highly modular, making it possible to develop plug-and-play implementations of crosscutting functionality. AspectJ provides more functionality than was covered by this short introduction. The next chapter, , covers in detail all the features of the AspectJ language. The following chapter, , then presents some carefully chosen examples that show you how AspectJ might be used. We recommend that you read the next two chapters carefully before deciding to adopt AspectJ into a project.