
\Ssect{AspectJ Solution}{aj}

\begin{figure*}
\scalefigfrom{0.27}{ajcache}
\caption{A graphical representation of the {\aj} solution}
\label{Fig:ajcache}
\end{figure*} 

The five aspects, three Java classes, and three interfaces that make up the {\aj} solution are shown in \Ref{Fig}{ajcache}.
The three classes are exactly the three original base classes of \Ref{Fig}{cachebase}, while the aspects are split into two abstract aspects aimed for reuse and three concrete aspects that attach and adapt the generic aspects to the details of the base. 
The abstract aspects and the base can each be compiled separately, while the concrete aspects cannot.
%%%
%%% JO Nov 15: wanted to add the following, but decided not to.
%%%\footnote{The situation is somewhat unclear: The three abstract aspects {\em can} be compiled separately, but need also to be recompiled along with the concrete aspects.}
%%% DL: Agreed, lets keep it out for now.
%%%

However, separate compilation is merely a performance optimization. 
We are more interested in whether any aspects can be separately understood, and whether they can be used in this solution without affecting other parts of a larger system.
The base (\type{Item}, \type{Simple}, \type{Container}) can certainly be understood in separation, if we compile without the concrete aspects.


\sssect{The Caching aspect} 
The \type{Caching} aspect in \Ref{Fig}{ajcache}
contains the inner interface \type{Cached}, which defines the role that the caching aspect is written over.
(Readers who know AspectJ may benefit from \Listing{cachingaspect}.)
Classes
playing the role \type{Cached} (by implementing the interface) can have one of
their
methods cached. 
The role requires a method \java{\itshape allInvalidated}, which should return all objects whose caches would be invalidated by a modification to the current object.
However, unlike Java interfaces, {\aj} interfaces can also provide member implementations---we use this ability to provide a \java{cachedValue} field and
a
\java{clearCache} method.
Note that at this stage we do not know which class(es) will implement the interface, but all implementing classes will be augmented with the provided behavior (and must in return provide an implementation of the required \java{\itshape allInvalidated} or be labeled \keywrd{abstract}).


\johan{pointcut? what's that? }

The \type{Caching} aspect  declares some abstract pointcuts representing the (as yet unknown) locations in the program that represent the method to be cached (\java{\itshape cache}) and the methods that invalidate such caches (\java{\itshape invalidate}).
These points will be advised: the invalidation points will call \java{clearCache}, while the method to be cached will only be executed if the cache is clear, caching the returned value, else it will just return the previously cached value.


\sssect{The Back aspect}

The \collab{Back} aspect is conceptually similar to the caching aspect,
in that we want to maintain an invariant, and will do so by intercepting
calls to methods that can affect the invariant.  All objects playing  the
\type{Source} role have vectors of \type{Target} objects.  The invariant
we wish to maintain is that we want each such \type{Target} to have a
back-link to the source in which it is contained.

We achieve this by augmenting (introducing, in {\aj} terminology) a backpointer to \type{Source} in all classes implementing the \type{Target} interface.
We also declare an abstract pointcut \java{associate}, which exposes the receiver and argument of each call to a method that modifies the target vector.

To maintain the invariant, we attach around advice to the abstract
pointcut, so that all calls to such methods are intercepted, and the
argument to the method call (the \type{Target} object being added) has
its back-pointer assigned the \type{Source} to which it is being added.
We use ``around'' advice rather than ``before'' advice as we need to
measure the length of the vector before and after the intercepted call:
only if the length increases, do we assume the \type{Target} was added
to the vector, and that its back-pointer should be set.~\footnote{%
        The issue isn't how general the backlink
        implementation is, but rather that we can flexibly reuse it.
}

\sssect{Superimposing the aspects}

Two concrete aspects connect the abstract aspects \type{Caching} and
\type{Back} to the base classes.  This is done by declaring that each
concrete aspect inherits from an abstract aspect.  The concrete aspect
must provide a definition for abstract pointcuts in the parent aspect
(indicated by dotted arrows in \Ref{Fig}{ajcache}).  The concrete aspects
additionally declare how the roles of the abstract aspects are played,
by declaring which base classes implement the interfaces (indicated by
filled arrows that run underneath the declaring aspects).

Concrete aspect {\color{green}\type{SuperimposeBack}} sets up the backlink
relationship, declaring that \type{Item} play the role of \type{Target},
and \type{Container} play the role of \type{Source}.  It also specifies
that \java{addItem} correspond to the \java{associate} pointcut.

Concrete aspect {\color{red}\type{SuperimposeCaching}} declares that \type{Item}
plays the role of \type{Cached}, and that methods \java{check}
and \java{addItem} should correspond to pointcuts \java{cache} and
\java{invalidate}, respectively.

Concrete aspect {\color{blue}\type{Adapt}} introduces the necessary
methods (\java{allInvalidated} and \java{getTargets}) so that the
abstract aspects' requirements are met, and no base classes  have to be
marked \keywrd{abstract}.~\footnote{The half-head arrow indicates that
\type{Adapt} provides behavior to \type{Container} without introducing
any additional typing relations.}

\Ssect{{\aj} Code}{ajcode}

Clarke and Walker's \Cite{ClaWal:2001:AJHJ} translation of composition
patterns to {\aj} is applicable to {\ac}s.  We follow their transformation
in spirit, if not to the letter, generating a surprisingly idiomatic
{\aj} program.  In our translation, we have attempted to produce reusable
aspects, so that the {\aj} solution
can be compared to the {\hj}~(\Ref{Section}{hj})
and {\ac}~(\Ref{Section}{ac}) solutions.

% -------------------
% -------------------


\lstinputlisting[caption={The Caching aspect in {\aj}.},label=Listing:cachingaspect,float=\fl]{examples/aj/Caching.java}

\Sssect{The Caching aspect in {\aj}}{cache-aj}

\Listing{cachingaspect} shows the {\aj} implementation of \type{Caching}.
We delay discussion of the use of interfaces to model participants until the \type{Back} aspect, as the discussion is more concrete in that context.

For simplicity, we assume that a cached method never returns \java{null},
and use this as a sentinel for cache validity.  An additional
\type{boolean} variable, as in the {\hj} example, could have been used
to keep track of the validity of the cached value.

% -------------------
% -------------------

\lstinputlisting[caption={The Back aspect in {\aj}.},label=Listing:backaspect,float=\fl]{examples/aj/Back.java}

\sssect{The Back aspect in {\aj}} 

\Listing{backaspect} shows the {\aj} implementation of \type{Back}.
We write an abstract aspect which is made concrete in a subclass by providing the necessary application-specific information.
{\aj} uses interfaces to declare types, which are then populated with behavior by introductions and \keywrd{implemented} by the base program, while the two other approaches' concerns declare their behavior in classes which are externally composed with the base program.

The situation in {\aj} is analogous to that of Java: it is considered good programming style to program against an interface, but up to the programmer to decide when and where to do so.
The {\aj} approach shares with Java the problem that one cannot instantiate an interface directly, but rather needs an abstract factory pattern. % \johan{get by w/o a reference?}.
We discuss the typing issues of interfaces pertaining to attachment in the section on invasiveness (\Ref{Section}{aj-invasivetypes}).

%% nov 15: slight rewording, s/deferred/required/g
Java interfaces describe the \type{Back} aspect's required interface.
Interfaces can only contain methods, thus the aspect's require interface cannot contain fields.
This can be worked around by instead adding getters and setters to the interface, and introducing methods to fulfill this interface.
Thus, in {\aj} the situation with fields is even more restrictive than in {\hj}, where we are forced to use comments to indicate a required field, but are able to compose them in the hypermodule.

%% nov 15: reorder clauses, sentences, parenthetical comment -> new sentence.
Required methods are declared directly on their interfaces, while provided behavior is in the aspect body.
Specifying an interface and its added behavior separately tangles the provided behavior for all the participants into one class body, and separates provided from required behavior textually.
The provided interface's members are added to host classes directly via {\aj}'s introduction mechanism, which interacts gracefully with interfaces, adding the introductions to the implementing class rather than the interface (which of course could not be an interface were it to contain code).

Advice is declared against abstract pointcuts.
{\aj} has a mature join point model, and we are easily able to express our intended behavior.
The format of the advice method differs from the {\ac} and {\hj} approach in that we explicitly pass in the receiver of \java{associate}, while \java{this} refers to the object representing the reified aspect.
This allows advice to be quite general, wrapping methods of varying signatures in different classes.
% forward reference to ac and hj

% -------------------
% -------------------

\lstinputlisting[caption={Concrete instances of the Aspects.},label=Listing:attachaspect,float=\fl]{examples/aj/Concrete1.java}

\Sssect{Implementing concrete aspects}{concr-aj}

%%%
%%% DL Nov 20: s/instantiated/implemented/
%%% DL: The term "instantiated" means making an instance from a class
%%%
\Listing{attachaspect} illustrates how the abstract aspects can
be implemented for the current application through sub-classing.
We attach the participant interfaces of the two abstract aspects to
classes by having the classes implement the interface.  We have moved
the \collab{adapt} concern into the connection package, as it is tightly
bound to both of the concerns it adapts.  {\aj} provides a very natural
way to specify this sort of adaptation code.

The implicit effect of supplying a concrete pointcut to the abstract
aspect is that its advice becomes attached to the application at the join
points specified.  As pointed out in \Ref{Section}{aj-invasivetypes},
type-invasiveness has implications for the runtime type-safety of
a program.

It was also fortunate that \collab{back} and \collab{cache} didn't
have any name clashes.  While {\aj} offers aspect-local methods for the
concern's implementation behavior, the expected methods on the interfaces
\emph{must} be implemented by public methods with exactly that name.

\Sssect{Summary}{aj-summary}
%%%
%%% DL: moved here for now
%%% JO Nov 17: ok, for now. I still think 3.5 is the ``right'' place.
%%% JO Nov 15: changed from \Ssssec{Static Safety}, moved one step later. Merge with Invasiveness?
%%% DL: Introduced summary 
%%% DL Nov 20: ssect "Generic Advice" hidden.
%%% DL Nov 20: ssect "Invasiveness" moved to 5.6.
%%% DL: Invasiveness was moved forward because it talks about aj, hj, and ac.
%%%\paragraph{Generic Advice}
%%%
\label{Section:unorthodoxgenericity}
The around \java{cache} advice illustrates the unconventional genericity mechanism of {\aj}'s around advice \Cite{AJ:ProgGuide}.
Notice that both the \java{around cache} caching advice, and the \java{cachedValue} field are of type \type{Object}. 
Around methods returning \type{Object} are able to advise methods of \emph{any} signature---including \type{void} and \type{int}.
We hope to be able to leverage subtype polymorphism  to reuse this aspect for caching methods of any signature.
However, the method we wish to cache returns an \type{int}, which isn't a subtype of \type{Object}, which would seem to make this a non-solution to our challenge problem. 
A feature of {\aj} resolves the quandary: if the return type is of primitive or \type{void} type, the cached method's result is transparently wrapped in a proxy object (in \java{check}'s case, an \type{Integer}) before being passed to the around advice, and likewise unwrapped before being returned to the caller of the [advised] cached method.
Not all return values are thus mapped: a returned null is left unchanged.
Unfortunately, this scheme is not statically type safe.
{\aj} \emph{will} catch many obvious type errors (such as so called stupid casts \Cite{IraPieWad:FJ}), but in some cases casting errors in unexpected places can result.
For example, if the  programmer were to assign a \type{String} to the \java{cachedValue} field, a dynamic casting error  will occur when we attempt to return this as the cached value of \java{check}, but would be allowed by the {\aj} compiler, as \type{String} is a subtype of \type{Object}.

%Understanding why this occurred requires the programmer to be a language ``wizard''.

