Home > Articles > Programming > Java

This chapter is from the book

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 class—think he's going 
for the System.out.println routine Jim?
Jim: It does look that way, Bob. Ah, yes, look—calling 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.20Figure 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.21Figure 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 pointcut—if 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.22Figure 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.23Figure 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.24Figure 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.25Figure 2.25 Hover help for declared warnings.

You can clearly see the text of our declare warning—a 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.26Figure 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.27Figure 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).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020