2.5 Stating the Notification Policy
How will we know whether our refactoring has succeeded? All the tests will pass, of course, but they do that now. The problem we want to address is the duplication and scattering of calls to notifyListeners throughout the policy hierarchy. If our refactoring is a success, there will be no calls to notifyListeners left in the policy hierarchy, and they will all have been replaced by a single call in the PolicyChangeNotification aspect. AspectJ enables us to capture requirements such as this directly in the code, and in this section you learn how. To do that, we need to introduce you to a couple of new concepts: join points and pointcuts.
2.5.1 Introducing Join Points
Programs live to execute, and when they execute, stuff happens. Methods get called, objects get initialized, fields are accessed and updated, constructors are executed, and so on. AspectJ calls these events that happen when a program is running join points. If program execution was a spectator sport, and you were commentating on the 2006 world championships, join points are the things that you would highlight in your commentary:
Bob: Looks like we're in for a good clean run today. Jim: Yes Bob, the classes are being fetched from disk now; I can't wait for this one to get started. Bob: We're off! The main class is loaded and the static initializer just ran. Jim: A traditional opening, executing the main method now ... Bob: Hmmm, accessing the "out" field on the old System classthink he's going for the System.out.println routine Jim? Jim: It does look that way, Bob. Ah, yes, lookcalling the println method, and that's a nice String there in the arguments. Bob: So, the println method is executing, you can almost feel the tension. Here it comes ... there's an H, an E, ... Jim: It is, it is, it's "Hello, World!". Very nicely done. Safely back from the call to println. Bob: Seems like the execution of the main method is just about done. Jim: They think it's all over ... It is now.
AspectJ supports join points for calls made to methods and constructors, for the actual execution of methods and constructors, for the initialization of classes and objects, for field accesses and updates, for the handling of exceptions, and a few more besides. Chapter 5 provides a more thorough introduction to join points.
Join points by themselves aren't all that exciting. Stuff has always happened when programs are executed. What is different in AOP and in AspectJ is that the programmer has a way to refer to join points from within the program. A way to say things such as, "Whenever you update the state of a policy object, notify all of its listeners." To the AspectJ compiler, that sentence looks a little bit more like this: "Whenever a join point that meets these conditions occurs (we'll call that a policyStateUpdate shall we?), call the notifyListeners method on the policy object."
2.5.2 Writing a Pointcut
The way that we specify which join points we are interested in is to write a pointcut. Pointcuts are like filters; as the program executes, a stream of join points occur, and it is the job of a pointcut to pick out the ones that it is interested in.2 The join points we are interested in right now are those that represent a call to the notifyListeners() method. When we make such a call, we are notifying the listeners. Here is what the pointcut declaration looks like in AspectJ:
pointcut notifyingListeners() : call(* PolicyImpl.notifyListeners(..));
Figure 2.20 shows the result of typing this into the aspect editor buffer and pressing Ctrl+S to save.
Figure 2.20 A pointcut declaration.
The syntax highlighting shows us that pointcut and call are keywords in the AspectJ language. Also note that the Outline view has updated to show the pointcut as a member of the aspect (just like a field or a method is a member of a class). We can use the Outline view to navigate in the editor buffer by selecting the nodes in the tree. For example, if we click the notifyingListeners() node in the Outline view, the selection in the editor is changed to the pointcut declaration, as shown in Figure 2.21.
Figure 2.21 Using the Outline view to navigate in the editor buffer.
The pointcut declaration declares a new pointcut called notifyingListeners (the name that appears in the Outline view). After a colon (:), comes the definition of which join points the notifyingListeners pointcut should match. In this case we are interested in join points that represent a call to certain methods. Inside the parentheses that follow the call keyword, we get to say which particular method calls we want to match: calls to the notifyListeners method defined in the PolicyImpl class. The first asterisk (*) in the expression is a wildcard that says we don't care what the return type of the method is, and the two periods (..) inside the notifyListeners(..) say that we don't care what arguments it takes. We know both of these things: The notifyListeners method takes no parameters and returns void, but they are not pertinent to our pointcutif the definition of the notifyListeners method were to change to take a parameter, or to return the number of listeners notified, we would still want the pointcut to match. By not specifying the details we don't care about, we make our program more robust in the face of change.
Chapter 6 explains everything you ever wanted to know about pointcuts and more; all that matters for the time being is that you get a feel for what a pointcut declaration looks like and what it does.
2.5.3 Using Declare Warning
This is all very nice, but the aspect still doesn't actually do anything. At the start of this section, we said that if our refactoring is a success, there will be no calls to notifyListeners left in the policy hierarchy, and they will all have been replaced by a single call in the PolicyChangeNotification aspect. So any call to the notifyListeners method that does not occur within the PolicyChangeNotification aspect breaks the modularity that we are trying to achieve. It would be useful at this point if we could find all such places. We can use an AspectJ construct known as declare warning to do just that. Let's declare it to be a compile time warning if anyone other than the PolicyChangeNotification aspect starts notifyingListeners. We can write it like this:
declare warning : notifyingListeners() && !within(PolicyChangeNotification) : "Only the PolicyChangeNotification aspect should be notifying listeners";
Figure 2.22 shows what happens when we type this into the editor buffer and press Ctrl+S to save.
Figure 2.22 Declare warning in the editor buffer.
We can see again from the syntax highlighting that declare warning is a keyword (pair of keywords to be precise) in the AspectJ language. The general form of the statement is this: "Declare it to be a compile-time warning, if any join point matching the following pointcut expression occurs, and this is the warning message I'd like you to use." In this particular case: "Declare it to be a compile-time warning, if any join point occurs that matches the notifyingListeners pointcut and is not within the PolicyChangeNotification aspect. At such points, issue a compile-time warning with the message 'Only the PolicyChangeNotification aspect should be notifying listeners.'"
If we turn our attention to the Outline view, we can see that something very interesting has happened, as shown in Figure 2.23.
Figure 2.23 Declare warning matches in the Outline view.
First of all, you can see that the declare warning appears in the Outline view as another kind of member within the aspect. There's also a plus sign (+) next to the declare warning node, indicating that there is content beneath it. If you expand this node you see matched by, and if you expand that node you see a list of all the places that are violating our policy of not calling notifyListeners outside of the PolicyChangeNotification aspect. There are 15 of them, and these nodes are actually hyperlinks that will take you directly to the offending statements in the program source code if you click them. Let's click the first entry in the list, HousePolicyImpl.setWorth. The editor opens on the HousePolicyImpl class, at the point where the call to notifyListeners is made, as shown in Figure 2.24.
Figure 2.24 Showing warnings in the workbench.
In the gutter of the editor buffer, next to the call to notifyListeners, you can see a warning icon. There are also warning decorations on the file icons for all the source files in which warnings have been found, as you can see in the Package Explorer, and in the titles of the files at the top of the Editor window. The gutter to the right of the editor buffer gives an overview of the whole source file. It shows us that there are two warnings in the file, one on the line we are looking at, and one farther down in the source file. Hovering over the warning in the editor brings up the tool tip shown in Figure 2.25.
Figure 2.25 Hover help for declared warnings.
You can clearly see the text of our declare warninga powerful way to get a message across to a programmer who inadvertently violates the intended encapsulation of change notification in the aspect. Having navigated to the HousePolicyImpl.java file using the Outline view, we can click the back button on the toolbar (see Figure 2.26) to go back to the PolicyChangeNotification aspect again. In this way, we can easily navigate back and forth.
Figure 2.26 Navigating back to the aspect.
Just in case you weren't getting the message that there are violations of the PolicyChangeNotification aspect's change notification rule by now, take a look at the Problems view as shown in Figure 2.27. You will see that a compiler warning message has been created for each join point that matches the pointcut we associated with the "declare warning" statement. These are just like any other compiler warning, and you can double-click them to navigate to the source of the problem.
Figure 2.27 We've got problems!
When we have successfully completed the refactoring, none of these warnings should remain.
How Can You Match Join Points at Compile Time?
The more astute readers will have noticed a slight anomaly in the descriptions we just gave in this section. Join points are events that occur during the runtime execution of a program, so how can a pointcut match any join points at compile time when the program isn't running? The answer is that it doesn't; but what the compiler can do, is look at a line of code containing a call to the notifyListeners method and say "when this program executes, that line of code is going to give rise to a join point that will match this pointcut." It is the results of this static analysis that display as warnings. Chapter 6 covers some kinds of pointcut expressions that cannot be fully evaluated at compile time. (They require a runtime test to confirm the match.) These kinds of pointcut expressions cannot be used with the declare warning statement (which obviously needs to know at compile time whether or not there is a match).