Home > Articles > Software Development & Management > Object Technology

1.4 Before/After Patterns

Many concurrent designs are best described as patterns. A pattern encapsulates a successful and common design form, usually an object structure (also known as a micro-architecture) consisting of one or more interfaces, classes, and/or objects that obey certain static and dynamic constraints and relationships. Patterns are an ideal vehicle for characterizing designs and techniques that need not be implemented in exactly the same way across different contexts, and thus cannot be usefully encapsulated as reusable components. Reusable components and frameworks can play a central role in concurrent software development. But much of concurrent OO programming entails the reuse, adaptation, and extension of recurring design forms and practices rather than of particular classes.

Unlike those in the pioneering Design Patterns book by Gamma, Helm, Johnson, and Vlissides (see Further Readings in 1.4.5), the patterns here are embedded within chapters discussing sets of related contexts and software design principles that generate the main forces and constraints resolved in the patterns. Many of these patterns are minor extensions or variants of other common OO layering and composition patterns. This section reviews some that are relied on heavily in subsequent chapters. Others are briefly described upon first encounter.

1.4.1 Layering

Layering policy control over mechanism is a common structuring principle in systems of all sorts. Many OO layering and composition techniques rely on sandwiching some method call or body of code between a given before-action and an after-action. All forms of before/after control arrange that a given ground method, say method, is intercepted so as always to execute in the sequence:

before(); method(); after();

Or, to ensure that after-actions are performed even if the ground methods encounter exceptions:

before();
try { method(); }
finally { after(); }

Most examples in this book of course revolve around concurrency control. For example, a synchronized method acquires a lock before executing the code inside the method, and releases the lock after the method otherwise completes. But the basic ideas of before/after patterns can be illustrated in conjunction with another useful practice in OO programming, self-checking code: The fields of any object should preserve all invariants whenever the object is not engaged in a public method (see 1.3.1). Invariants should be maintained even if these methods throw any of their declared exceptions, unless these exceptions denote corruption or program failure (as may be true for RuntimeExceptions and Errors).

Conformance to computable invariants can be tested dynamically by creating classes that check them both on entry to and on exit from every public method. Similar techniques apply to preconditions and postconditions, but for simplicity, we'll illustrate only with invariants.

As an example, suppose we'd like to create water tank classes that contain a self-check on the invariant that the volume is always between zero and the capacity. To do this, we can define a checkVolumeInvariant method and use it as both the before and after operation. We can first define an exception to throw if the invariant fails:

class AssertionError extends java.lang.Error {
 public AssertionError() { super(); }
 public AssertionError(String message) { super(message); }
}

It can be disruptive to insert these checks manually inside each method. Instead, one of three before/after design patterns can be used to separate the checks from the ground methods: adapter classes, subclass-based designs, and method adapter classes.

In all cases, the best way to set this up is to define an interface describing the basic functionality. Interfaces are almost always necessary when you need to give yourself enough room to vary implementations. Conversely, the lack of existing interfaces limits options when retrospectively applying before/after patterns.

Here is an interface describing a minor variant of the water tank class discussed in 1.2.4. Before/after techniques may be applied to check invariants around the transferWater operation.

interface Tank { 
 float getCapacity();
 float getVolume();
 void transferWater(float amount) 
      throws OverflowException, UnderflowException;
}

1.4.2 Adapters

When standardized interfaces are defined after designing one or more concrete classes, these classes often do not quite implement the desired interface. For example, the names of their methods might be slightly different from those defined in the interface. If you cannot modify these concrete classes to fix such problems, you can still obtain the desired effect by building an Adapter class that translates away the incompatibilities.

Say you have a Performer class that supports method perform and meets all the qualifications of being usable as a Runnable except for the name mismatch. You can build an Adapter so it can be used in a thread by some other class:

Figure 1-20

class AdaptedPerformer implements Runnable {
private final Performer adaptee;

 public AdaptedPerformer(Performer p) { adaptee = p; }
 public void run() { adaptee.perform(); }
}

This is only one of many common contexts for building Adapters, which also form the basis of several related patterns presented in the Design Patterns book. A Proxy is an Adapter with the same interface as its delegate. A Composite maintains a collection of delegates, all supporting the same interface.

In this delegation-based style of composition, the publicly accessible host class forwards all methods to one or more delegates and relays back replies, perhaps doing some light translation (name changes, parameter coercion, result filtering, etc.) surrounding the delegate calls.

Adapters can be used to provide before/after control merely by wrapping the delegated call within the control actions. For example, assuming that we have an implementation class, say TankImpl, we can write the following AdaptedTank class. This class can be used instead of the original in some application by replacing all occurrences of:

new TankImpl(...)

with:

new AdaptedTank(new TankImpl(...)).
class AdaptedTank implements Tank { 
 protected final Tank delegate;

 public AdaptedTank(Tank t) { delegate = t; }

 public float getCapacity() { return delegate.getCapacity(); }

 public float getVolume() { return delegate.getVolume(); }

 protected void checkVolumeInvariant() throws AssertionError {
  float v = getVolume();
  float c = getCapacity();
  if ( !(v >= 0.0 && v <= c) )
   throw new AssertionError();
 }

 public synchronized void transferWater(float amount) 
  throws OverflowException, UnderflowException {

  checkVolumeInvariant(); // before-check

  try {
   delegate.transferWater(amount);
  }

  // The re-throws will be postponed until after-check
  //  in the finally clause

  catch (OverflowException ex) { throw ex; }
  catch (UnderflowException ex) { throw ex; }

  finally {
   checkVolumeInvariant(); // after-check
  }
 }
}

1.4.3 Subclassing

In the normal case, when the intercepted before/after versions of methods have the same names and usages as base versions, subclassing can be a simpler alternative to the use of Adapters. Subclass versions of methods can interpose checks around calls to their super versions. For example:

class SubclassedTank extends TankImpl { 

 protected void checkVolumeInvariant() throws AssertionError {
  // ... identical to AdaptedTank version ...
 }

 public synchronized void transferWater(float amount) 
  throws OverflowException, UnderflowException {
  // identical to AdaptedTank version except for inner call:

  // ...
  try {
   super.transferWater(amount);
  }
  // ...
 }
}

Some choices between subclassing and Adapters are just a matter of style. Others reflect differences between delegation and inheritance.

Figure 1-21

Adapters permit manipulations that escape subclassing rules. For example, you cannot override a public method as private in a subclass in order to disable access, but you can simply fail to relay the method in an Adapter. Various forms of delegation can even be used as a substitute of sorts for subclassing by having each "sub" class (Adapter) hold a reference to an instance of its "super" class (Adaptee), forwarding it all "inherited" operations. Such Adapters often have exactly the same interfaces as their delegates, in which case they are considered to be simple kinds of Proxies. Delegation can also be more flexible than subclassing, since "sub" objects can even change their "supers" (by reassigning the delegate reference) dynamically.

Delegation can also be used to obtain the effects of multiple code inheritance. For example, if a class must implement two unrelated interfaces, say Tank and java.awt.event.ActionListener, and there are two available superclasses providing the needed functionality, then one of these may be subclassed and the other delegated.

However, delegation is less powerful than subclassing in some other respects. For example, self-calls in "superclasses" are not automatically bound to the versions of methods that have been "overridden" in delegation-based "subclasses". Adapter designs can also run into snags revolving around the fact that the Adaptee and Adapter objects are different objects. For example, object reference equality tests must be performed more carefully since a test to see if you have the Adaptee version of an object fails if you have the Adapter version, and vice versa.

Most of these problems can be avoided via the extreme measure of declaring all methods in Adaptee classes to take an "apparent self" argument referring to the Adapter, and always using it instead of this, even for self-calls and identity checks (for example by overriding Object.equals). Some people reserve the term delegation for objects and classes written in this style rather than the forwarding techniques that are almost always used to implement simple Adapters.

1.4.3.1 Template methods

When you are pretty sure that you are going to rely on before/after control in a set of related classes, you can create an abstract class that automates the control sequence via an application of the Template Method pattern (which has nothing to do with C++ generic types).

Figure 1-22

An abstract class supporting template methods sets up a framework facilitating construction of subclasses that may override the ground-level actions, the before/after methods, or both:

  • Basic ground-level action code is defined in non-public methods. (By convention, we name the non-public version of any method method as doMethod.) Somewhat less flexibly, these methods need not be declared non-public if they are instead designed to be overridden in subclasses.

  • Before and after operations are also defined as non-public methods.

  • Public methods invoke the ground methods between the before and after methods.

Applying this to the Tank example leads to:

abstract class AbstractTank implements Tank { 
 protected void checkVolumeInvariant() throws AssertionError {
  // ... identical to AdaptedTank version ...
 }

 protected abstract void doTransferWater(float amount) 
  throws OverflowException, UnderflowException;

 public synchronized void transferWater(float amount) 
  throws OverflowException, UnderflowException {
  // identical to AdaptedTank version except for inner call:

  // ...
  try {
   doTransferWater(amount);
  }
  // ...
 }
}

class ConcreteTank extends AbstractTank {
 protected final float capacity;
 protected float volume;
 // ...
 public float getVolume() { return volume; }
 public float getCapacity() { return capacity; }

 protected void doTransferWater(float amount) 
  throws OverflowException, UnderflowException { 
  // ... implementation code ...
 }
}

1.4.4 Method Adapters

The most flexible, but sometimes most awkward approach to before/after control is to define a class whose entire purpose is to invoke a particular method on a particular object. In the Command Object pattern and its many variants, instances of such classes can then be passed around, manipulated, and ultimately executed (here, between before/after operations).

Because of static typing rules, there must be a different kind of adapter class for each kind of method being wrapped. To avoid proliferation of all these types, most applications restrict attention to only one or a small set of generic interfaces, each defining a single method. For example, the Thread class and most other execution frameworks accept only instances of interface Runnable in order to invoke their argumentless, resultless, exceptionless run methods. Similarly, in 4.3.3.1, we define and use interface Callable containing only a method call that accepts one Object argument, returns an Object, and may throw any Exception.

In more focused applications, you can define any suitable single-method interface, instantiate an implementation — almost always via an anonymous inner class — and then pass it around for later execution. This technique is used extensively in the java.awt and javax.swing packages, which define interfaces and abstract classes associated with different kinds of event-handling methods. (In some other languages, function pointers and closures are defined and used to achieve some of these effects.)

We can apply a version of before/after layering based on method adapters here by first defining a TankOp interface:

interface TankOp {
 void op() throws OverflowException, UnderflowException;
}

In the following sample code, uncharacteristically, all uses of method adapters are local to the TankWithMethodAdapter class. Also, in this tiny example, there is only one wrappable method. However, the same scaffolding could be used for any other Tank methods defined in this class or its subclasses. Method adapters are much more common in applications where instances must be registered and/or passed around among multiple objects before being executed, which justifies the extra setup costs and programming obligations.

class TankWithMethodAdapter {
 // ...
 protected void checkVolumeInvariant() throws AssertionError { 
  // ... identical to AdaptedTank version ...
 }

 protected void runWithinBeforeAfterChecks(TankOp cmd) 
  throws OverflowException, UnderflowException {
  // identical to AdaptedTank.transferWater 
  //  except for inner call:

  // ...
  try {
   cmd.op();
  }
  // ...
 }

 protected void doTransferWater(float amount) 
  throws OverflowException, UnderflowException { 
  // ... implementation code ...
 }

 public synchronized void transferWater(final float amount) 
  throws OverflowException, UnderflowException {

  runWithinBeforeAfterChecks(new TankOp() {
   public void op() 
    throws OverflowException, UnderflowException {
     doTransferWater(amount);
   }
  });
 }
}

Some applications of method adapters can be partially automated by using reflection facilities. A generic constructor can probe a class for a particular java.lang.reflect.Method, set up arguments for it, invoke it, and transfer back results. This comes at the price of weaker static guarantees, greater overhead, and the need to deal with the many exceptions that can arise. So this is generally only worthwhile when dealing with unknown dynamically loaded code.

More extreme and exotic reflective interception techniques are available if you escape the confines of the language. For example, it is possible to create and apply tools that splice bytecodes representing before and after actions into compiled class representations or do so upon class-loading.

1.4.5 Further Readings

There are many useful design patterns besides those that are particular to concurrent programming, and surely many others relating to concurrency that are not included in this book. Other books presenting patterns and pattern-related aspects of software design include:

    Buschmann, Frank, Regine Meunier, Hans Rohnert, Peter Sommerlad, and Michael Stal. Pattern-Oriented Software Architecture: A System of Patterns, Wiley, 1996.

    Coplien, James. Advanced C++: Programming Styles and Idioms, Addison-Wesley, 1992.

    Fowler, Martin. Analysis Patterns, Addison-Wesley, 1997

    Gamma, Erich, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns, Addison-Wesley, 1994. (The "Gang of Four" book.)

    Rising, Linda. The Patterns Handbook, Cambridge University Press, 1998.

    Shaw, Mary, and David Garlan. Software Architecture, Prentice Hall, 1996.

    (Various editors) Pattern Languages of Program Design, Addison-Wesley. This series incorporates patterns presented at the annual Pattern Languages of Programming (PLoP) conference.

The OO language Self is among the few that directly support a pure delegation-based style of programming without requiring explicit message forwarding. See:

    Ungar, David. "The Self Papers", Lisp and Symbolic Computation, 1991.

Reflective before/after techniques are often seen in Lisp, Scheme and CLOS (the Common Lisp Object System). See, for example:

    Abelson, Harold, and Gerald Sussman. Structure and Interpretation of Computer Programs, MIT Press, 1996.

    Kiczales, Gregor, Jim des Rivieres, and Daniel Bobrow. The Art of the Metaobject Protocol, MIT Press, 1993.

Additional layered synchronization design patterns are discussed in:

    Rito Silva, Ant nio, Jo o Pereira and Jos Alves Marques. "Object Synchronizer", in Neil Harrison, Brian Foote and Hans Rohnert (eds.), Pattern Languages of Program Design, Volume 4, Addison-Wesley, 1999.

A compositional approach to layering concurrency control is described in:

    Holmes, David. Synchronisation Rings: Composable Synchronisation for Concurrent Object Oriented Systems, PhD Thesis, Macquarie University, 1999.

Composition of collections of before/after methods that deal with different aspects of functionality (for example, mixing synchronization control with persistence control) may require more elaborate frameworks than discussed here. One approach is to construct a metaclass framework that partially automates the interception and wrapping of methods by class objects. For an extensive analysis and discussion of the resulting composition techniques, see:

    Forman, Ira, and Scott Danforth. Putting Metaclasses to Work, Addison-Wesley, 1999.

Aspect-oriented programming replaces layered before/after techniques with tools that weave together code dealing with different aspects of control. Reports on the language AspectJ include some examples from this book expressed in an aspect-oriented fashion. See:

    Kiczales, Gregor, John Lamping, Anurag Mendhekar, Chris Maeda, Cristina Videira Lopes, Jean-Marc Loingtier, and John Irwin. "Aspect-Oriented Programming", Proceedings of the European Conference on Object-Oriented Programming (ECOOP), 1997.

Several tools are available for partially automating invariant tests. See, for example:

    Beck, Kent, and Erich Gamma. "Test Infected: Programmers Love Writing Tests", The Java Report, July 1998.

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