You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

gettingstarted.adoc 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. [[starting]]
  2. = Getting Started with AspectJ
  3. [[starting-intro]]
  4. == Introduction
  5. Many software developers are attracted to the idea of aspect-oriented
  6. programming (AOP) but unsure about how to begin using the technology.
  7. They recognize the concept of crosscutting concerns, and know that they
  8. have had problems with the implementation of such concerns in the past.
  9. But there are many questions about how to adopt AOP into the development
  10. process. Common questions include:
  11. * Can I use aspects in my existing code?
  12. * What kinds of benefits can I expect to get from using aspects?
  13. * How do I find aspects in my programs?
  14. * How steep is the learning curve for AOP?
  15. * What are the risks of using this new technology?
  16. This chapter addresses these questions in the context of AspectJ: a
  17. general-purpose aspect-oriented extension to Java. A series of abridged
  18. examples illustrate the kinds of aspects programmers may want to
  19. implement using AspectJ and the benefits associated with doing so.
  20. Readers who would like to understand the examples in more detail, or who
  21. want to learn how to program examples like these, can find more complete
  22. examples and supporting material linked from the
  23. https://www.eclipse.org/aspectj/[AspectJ web site].
  24. A significant risk in adopting any new technology is going too far too
  25. fast. Concern about this risk causes many organizations to be
  26. conservative about adopting new technology. To address this issue, the
  27. examples in this chapter are grouped into three broad categories, with
  28. aspects that are easier to adopt into existing development projects
  29. coming earlier in this chapter. The next section,
  30. xref:#starting-aspectj[Introduction to AspectJ], we present the core of
  31. AspectJ's features, and in xref:#starting-development[Development
  32. Aspects], we present aspects that facilitate tasks such as debugging,
  33. testing and performance tuning of applications. And, in the section
  34. following, xref:#starting-production[Production Aspects], we present
  35. aspects that implement crosscutting functionality common in Java
  36. applications. We will defer discussing a third category of aspects,
  37. reusable aspects, until xref:language.adoc#language[The AspectJ Language].
  38. These categories are informal, and this ordering is not the only way to
  39. adopt AspectJ. Some developers may want to use a production aspect right
  40. away. But our experience with current AspectJ users suggests that this
  41. is one ordering that allows developers to get experience with (and
  42. benefit from) AOP technology quickly, while also minimizing risk.
  43. [[starting-aspectj]]
  44. == Introduction to AspectJ
  45. This section presents a brief introduction to the features of AspectJ
  46. used later in this chapter. These features are at the core of the
  47. language, but this is by no means a complete overview of AspectJ.
  48. The features are presented using a simple figure editor system. A
  49. `Figure` consists of a number of `FigureElements`, which can be either
  50. ``Point``s or ``Line``s. The `Figure` class provides factory services. There
  51. is also a `Display`. Most example programs later in this chapter are
  52. based on this system as well.
  53. image:images/figureUML.png[ UML for the `FigureEditor` example ]
  54. The motivation for AspectJ (and likewise for aspect-oriented
  55. programming) is the realization that there are issues or concerns that
  56. are not well captured by traditional programming methodologies. Consider
  57. the problem of enforcing a security policy in some application. By its
  58. nature, security cuts across many of the natural units of modularity of
  59. the application. Moreover, the security policy must be uniformly applied
  60. to any additions as the application evolves. And the security policy
  61. that is being applied might itself evolve. Capturing concerns like a
  62. security policy in a disciplined way is difficult and error-prone in a
  63. traditional programming language.
  64. Concerns like security cut across the natural units of modularity. For
  65. object-oriented programming languages, the natural unit of modularity is
  66. the class. But in object-oriented programming languages, crosscutting
  67. concerns are not easily turned into classes precisely because they cut
  68. across classes, and so these aren't reusable, they can't be refined or
  69. inherited, they are spread through out the program in an undisciplined
  70. way, in short, they are difficult to work with.
  71. Aspect-oriented programming is a way of modularizing crosscutting
  72. concerns much like object-oriented programming is a way of modularizing
  73. common concerns. AspectJ is an implementation of aspect-oriented
  74. programming for Java.
  75. AspectJ adds to Java just one new concept, a join point -- and that's
  76. really just a name for an existing Java concept. It adds to Java only a
  77. few new constructs: pointcuts, advice, inter-type declarations and
  78. aspects. Pointcuts and advice dynamically affect program flow,
  79. inter-type declarations statically affects a program's class hierarchy,
  80. and aspects encapsulate these new constructs.
  81. A _join point_ is a well-defined point in the program flow. A _pointcut_
  82. picks out certain join points and values at those points. A piece of
  83. _advice_ is code that is executed when a join point is reached. These
  84. are the dynamic parts of AspectJ.
  85. AspectJ also has different kinds of _inter-type declarations_ that allow
  86. the programmer to modify a program's static structure, namely, the
  87. members of its classes and the relationship between classes.
  88. AspectJ's _aspect_ are the unit of modularity for crosscutting concerns.
  89. They behave somewhat like Java classes, but may also include pointcuts,
  90. advice and inter-type declarations.
  91. In the sections immediately following, we are first going to look at
  92. join points and how they compose into pointcuts. Then we will look at
  93. advice, the code which is run when a pointcut is reached. We will see
  94. how to combine pointcuts and advice into aspects, AspectJ's reusable,
  95. inheritable unit of modularity. Lastly, we will look at how to use
  96. inter-type declarations to deal with crosscutting concerns of a
  97. program's class structure.
  98. === The Dynamic Join Point Model
  99. A critical element in the design of any aspect-oriented language is the
  100. join point model. The join point model provides the common frame of
  101. reference that makes it possible to define the dynamic structure of
  102. crosscutting concerns. This chapter describes AspectJ's dynamic join
  103. points, in which join points are certain well-defined points in the
  104. execution of the program.
  105. AspectJ provides for many kinds of join points, but this chapter
  106. discusses only one of them: method call join points. A method call join
  107. point encompasses the actions of an object receiving a method call. It
  108. includes all the actions that comprise a method call, starting after all
  109. arguments are evaluated up to and including return (either normally or
  110. by throwing an exception).
  111. Each method call at runtime is a different join point, even if it comes
  112. from the same call expression in the program. Many other join points may
  113. run while a method call join point is executing -- all the join points
  114. that happen while executing the method body, and in those methods called
  115. from the body. We say that these join points execute in the _dynamic
  116. context_ of the original call join point.
  117. [[pointcuts-starting]]
  118. === Pointcuts
  119. In AspectJ, _pointcuts_ pick out certain join points in the program
  120. flow. For example, the pointcut
  121. [source, java]
  122. ....
  123. call(void Point.setX(int))
  124. ....
  125. picks out each join point that is a call to a method that has the
  126. signature `void Point.setX(int)` - that is, ``Point``'s void `setX` method
  127. with a single `int` parameter.
  128. A pointcut can be built out of other pointcuts with and, or, and not
  129. (spelled `&&`, `||`, and `!`). For example:
  130. [source, java]
  131. ....
  132. call(void Point.setX(int)) ||
  133. call(void Point.setY(int))
  134. ....
  135. picks out each join point that is either a call to `setX` or a call to
  136. `setY`.
  137. Pointcuts can identify join points from many different types - in other
  138. words, they can crosscut types. For example,
  139. [source, java]
  140. ....
  141. call(void FigureElement.setXY(int,int)) ||
  142. call(void Point.setX(int)) ||
  143. call(void Point.setY(int)) ||
  144. call(void Line.setP1(Point)) ||
  145. call(void Line.setP2(Point));
  146. ....
  147. picks out each join point that is a call to one of five methods (the
  148. first of which is an interface method, by the way).
  149. In our example system, this pointcut captures all the join points when a
  150. `FigureElement` moves. While this is a useful way to specify this
  151. crosscutting concern, it is a bit of a mouthful. So AspectJ allows
  152. programmers to define their own named pointcuts with the `pointcut`
  153. form. So the following declares a new, named pointcut:
  154. [source, java]
  155. ....
  156. pointcut move():
  157. call(void FigureElement.setXY(int,int)) ||
  158. call(void Point.setX(int)) ||
  159. call(void Point.setY(int)) ||
  160. call(void Line.setP1(Point)) ||
  161. call(void Line.setP2(Point));
  162. ....
  163. and whenever this definition is visible, the programmer can simply use
  164. `move()` to capture this complicated pointcut.
  165. The previous pointcuts are all based on explicit enumeration of a set of
  166. method signatures. We sometimes call this _name-based_ crosscutting.
  167. AspectJ also provides mechanisms that enable specifying a pointcut in
  168. terms of properties of methods other than their exact name. We call this
  169. _property-based_ crosscutting. The simplest of these involve using
  170. wildcards in certain fields of the method signature. For example, the
  171. pointcut
  172. [source, java]
  173. ....
  174. call(void Figure.make*(..))
  175. ....
  176. picks out each join point that's a call to a void method defined on
  177. `Figure` whose the name begins with "`make`" regardless of the method's
  178. parameters. In our system, this picks out calls to the factory methods
  179. `makePoint` and `makeLine`. The pointcut
  180. [source, java]
  181. ....
  182. call(public * Figure.* (..))
  183. ....
  184. picks out each call to ``Figure``'s public methods.
  185. But wildcards aren't the only properties AspectJ supports. Another
  186. pointcut, `cflow`, identifies join points based on whether they occur in
  187. the dynamic context of other join points. So
  188. [source, java]
  189. ....
  190. cflow(move())
  191. ....
  192. picks out each join point that occurs in the dynamic context of the join
  193. points picked out by `move()`, our named pointcut defined above. So this
  194. picks out each join points that occurrs between when a move method is
  195. called and when it returns (either normally or by throwing an
  196. exception).
  197. [[advice-starting]]
  198. === Advice
  199. So pointcuts pick out join points. But they don't _do_ anything apart
  200. from picking out join points. To actually implement crosscutting
  201. behavior, we use advice. Advice brings together a pointcut (to pick out
  202. join points) and a body of code (to run at each of those join points).
  203. AspectJ has several different kinds of advice. _Before advice_ runs as a
  204. join point is reached, before the program proceeds with the join point.
  205. For example, before advice on a method call join point runs before the
  206. actual method starts running, just after the arguments to the method
  207. call are evaluated.
  208. [source, java]
  209. ....
  210. before(): move() {
  211. System.out.println("about to move");
  212. }
  213. ....
  214. _After advice_ on a particular join point runs after the program
  215. proceeds with that join point. For example, after advice on a method
  216. call join point runs after the method body has run, just before before
  217. control is returned to the caller. Because Java programs can leave a
  218. join point 'normally' or by throwing an exception, there are three kinds
  219. of after advice: `after returning`, `after
  220. throwing`, and plain `after` (which runs after returning _or_
  221. throwing, like Java's `finally`).
  222. [source, java]
  223. ....
  224. after() returning: move() {
  225. System.out.println("just successfully moved");
  226. }
  227. ....
  228. _Around advice_ on a join point runs as the join point is reached, and
  229. has explicit control over whether the program proceeds with the join
  230. point. Around advice is not discussed in this section.
  231. ==== Exposing Context in Pointcuts
  232. Pointcuts not only pick out join points, they can also expose part of
  233. the execution context at their join points. Values exposed by a pointcut
  234. can be used in the body of advice declarations.
  235. An advice declaration has a parameter list (like a method) that gives
  236. names to all the pieces of context that it uses. For example, the after
  237. advice
  238. [source, java]
  239. ....
  240. after(FigureElement fe, int x, int y) returning:
  241. // SomePointcut...
  242. {
  243. // SomeBody
  244. }
  245. ....
  246. uses three pieces of exposed context, a `FigureElement` named fe, and
  247. two ``int``s named x and y.
  248. The body of the advice uses the names just like method parameters, so
  249. [source, java]
  250. ....
  251. after(FigureElement fe, int x, int y) returning:
  252. // SomePointcut...
  253. {
  254. System.out.println(fe + " moved to (" + x + ", " + y + ")");
  255. }
  256. ....
  257. The advice's pointcut publishes the values for the advice's arguments.
  258. The three primitive pointcuts `this`, `target` and `args` are used to
  259. publish these values. So now we can write the complete piece of advice:
  260. [source, java]
  261. ....
  262. after(FigureElement fe, int x, int y) returning:
  263. call(void FigureElement.setXY(int, int))
  264. && target(fe)
  265. && args(x, y)
  266. {
  267. System.out.println(fe + " moved to (" + x + ", " + y + ")");
  268. }
  269. ....
  270. The pointcut exposes three values from calls to `setXY`: the target
  271. `FigureElement` -- which it publishes as `fe`, so it becomes the first
  272. argument to the after advice -- and the two int arguments -- which it
  273. publishes as `x` and `y`, so they become the second and third argument
  274. to the after advice.
  275. So the advice prints the figure element that was moved and its new `x`
  276. and `y` coordinates after each `setXY` method call.
  277. A named pointcut may have parameters like a piece of advice. When the
  278. named pointcut is used (by advice, or in another named pointcut), it
  279. publishes its context by name just like the `this`, `target` and `args`
  280. pointcut. So another way to write the above advice is
  281. [source, java]
  282. ....
  283. pointcut setXY(FigureElement fe, int x, int y):
  284. call(void FigureElement.setXY(int, int))
  285. && target(fe)
  286. && args(x, y);
  287. after(FigureElement fe, int x, int y) returning: setXY(fe, x, y) {
  288. System.out.println(fe + " moved to (" + x + ", " + y + ").");
  289. }
  290. ....
  291. === Inter-type declarations
  292. Inter-type declarations in AspectJ are declarations that cut across
  293. classes and their hierarchies. They may declare members that cut across
  294. multiple classes, or change the inheritance relationship between
  295. classes. Unlike advice, which operates primarily dynamically,
  296. introduction operates statically, at compile-time.
  297. Consider the problem of expressing a capability shared by some existing
  298. classes that are already part of a class hierarchy, i.e. they already
  299. extend a class. In Java, one creates an interface that captures this new
  300. capability, and then adds to _each affected class_ a method that
  301. implements this interface.
  302. AspectJ can express the concern in one place, by using inter-type
  303. declarations. The aspect declares the methods and fields that are
  304. necessary to implement the new capability, and associates the methods
  305. and fields to the existing classes.
  306. Suppose we want to have `Screen` objects observe changes to `Point`
  307. objects, where `Point` is an existing class. We can implement this by
  308. writing an aspect declaring that the class Point `Point` has an instance
  309. field, `observers`, that keeps track of the `Screen` objects that are
  310. observing ``Point``s.
  311. [source, java]
  312. ....
  313. aspect PointObserving {
  314. private Vector Point.observers = new Vector();
  315. // ...
  316. }
  317. ....
  318. The `observers` field is private, so only `PointObserving` can see it.
  319. So observers are added or removed with the static methods `addObserver`
  320. and `removeObserver` on the aspect.
  321. [source, java]
  322. ....
  323. aspect PointObserving {
  324. private Vector Point.observers = new Vector();
  325. public static void addObserver(Point p, Screen s) {
  326. p.observers.add(s);
  327. }
  328. public static void removeObserver(Point p, Screen s) {
  329. p.observers.remove(s);
  330. }
  331. //...
  332. }
  333. ....
  334. Along with this, we can define a pointcut `changes` that defines what we
  335. want to observe, and the after advice defines what we want to do when we
  336. observe a change.
  337. [source, java]
  338. ....
  339. aspect PointObserving {
  340. private Vector Point.observers = new Vector();
  341. public static void addObserver(Point p, Screen s) {
  342. p.observers.add(s);
  343. }
  344. public static void removeObserver(Point p, Screen s) {
  345. p.observers.remove(s);
  346. }
  347. pointcut changes(Point p): target(p) && call(void Point.set*(int));
  348. after(Point p): changes(p) {
  349. Iterator iter = p.observers.iterator();
  350. while ( iter.hasNext() ) {
  351. updateObserver(p, (Screen)iter.next());
  352. }
  353. }
  354. static void updateObserver(Point p, Screen s) {
  355. s.display(p);
  356. }
  357. }
  358. ....
  359. Note that neither ``Screen``'s nor ``Point``'s code has to be modified, and
  360. that all the changes needed to support this new capability are local to
  361. this aspect.
  362. === Aspects
  363. Aspects wrap up pointcuts, advice, and inter-type declarations in a a
  364. modular unit of crosscutting implementation. It is defined very much
  365. like a class, and can have methods, fields, and initializers in addition
  366. to the crosscutting members. Because only aspects may include these
  367. crosscutting members, the declaration of these effects is localized.
  368. Like classes, aspects may be instantiated, but AspectJ controls how that
  369. instantiation happens -- so you can't use Java's `new` form to build new
  370. aspect instances. By default, each aspect is a singleton, so one aspect
  371. instance is created. This means that advice may use non-static fields of
  372. the aspect, if it needs to keep state around:
  373. [source, java]
  374. ....
  375. aspect Logging {
  376. OutputStream logStream = System.err;
  377. before(): move() {
  378. logStream.println("about to move");
  379. }
  380. }
  381. ....
  382. Aspects may also have more complicated rules for instantiation, but
  383. these will be described in a later chapter.
  384. [[starting-development]]
  385. == Development Aspects
  386. The next two sections present the use of aspects in increasingly
  387. sophisticated ways. Development aspects are easily removed from
  388. production builds. Production aspects are intended to be used in both
  389. development and in production, but tend to affect only a few classes.
  390. This section presents examples of aspects that can be used during
  391. development of Java applications. These aspects facilitate debugging,
  392. testing and performance tuning work. The aspects define behavior that
  393. ranges from simple tracing, to profiling, to testing of internal
  394. consistency within the application. Using AspectJ makes it possible to
  395. cleanly modularize this kind of functionality, thereby making it
  396. possible to easily enable and disable the functionality when desired.
  397. === Tracing
  398. This first example shows how to increase the visibility of the internal
  399. workings of a program. It is a simple tracing aspect that prints a
  400. message at specified method calls. In our figure editor example, one
  401. such aspect might simply trace whenever points are drawn.
  402. [source, java]
  403. ....
  404. aspect SimpleTracing {
  405. pointcut tracedCall():
  406. call(void FigureElement.draw(GraphicsContext));
  407. before(): tracedCall() {
  408. System.out.println("Entering: " + thisJoinPoint);
  409. }
  410. }
  411. ....
  412. This code makes use of the `thisJoinPoint` special variable. Within all
  413. advice bodies this variable is bound to an object that describes the
  414. current join point. The effect of this code is to print a line like the
  415. following every time a figure element receives a `draw` method call:
  416. [source, text]
  417. ....
  418. Entering: call(void FigureElement.draw(GraphicsContext))
  419. ....
  420. To understand the benefit of coding this with AspectJ consider changing
  421. the set of method calls that are traced. With AspectJ, this just
  422. requires editing the definition of the `tracedCalls` pointcut and
  423. recompiling. The individual methods that are traced do not need to be
  424. edited.
  425. When debugging, programmers often invest considerable effort in figuring
  426. out a good set of trace points to use when looking for a particular kind
  427. of problem. When debugging is complete or appears to be complete it is
  428. frustrating to have to lose that investment by deleting trace statements
  429. from the code. The alternative of just commenting them out makes the
  430. code look bad, and can cause trace statements for one kind of debugging
  431. to get confused with trace statements for another kind of debugging.
  432. With AspectJ it is easy to both preserve the work of designing a good
  433. set of trace points and disable the tracing when it isn't being used.
  434. This is done by writing an aspect specifically for that tracing mode,
  435. and removing that aspect from the compilation when it is not needed.
  436. This ability to concisely implement and reuse debugging configurations
  437. that have proven useful in the past is a direct result of AspectJ
  438. modularizing a crosscutting design element the set of methods that are
  439. appropriate to trace when looking for a given kind of information.
  440. === Profiling and Logging
  441. Our second example shows you how to do some very specific profiling.
  442. Although many sophisticated profiling tools are available, and these can
  443. gather a variety of information and display the results in useful ways,
  444. you may sometimes want to profile or log some very specific behavior. In
  445. these cases, it is often possible to write a simple aspect similar to
  446. the ones above to do the job.
  447. For example, the following aspect counts the number of calls to the
  448. `rotate` method on a `Line` and the number of calls to the `set*`
  449. methods of a `Point` that happen within the control flow of those calls
  450. to `rotate`:
  451. [source, java]
  452. ....
  453. aspect SetsInRotateCounting {
  454. int rotateCount = 0;
  455. int setCount = 0;
  456. before(): call(void Line.rotate(double)) {
  457. rotateCount++;
  458. }
  459. before():
  460. call(void Point.set*(int)) &&
  461. cflow(call(void Line.rotate(double)))
  462. {
  463. setCount++;
  464. }
  465. }
  466. ....
  467. In effect, this aspect allows the programmer to ask very specific
  468. questions like
  469. ____
  470. How many times is the `rotate` method defined on `Line` objects called?
  471. ____
  472. and
  473. ____
  474. How many times are methods defined on `Point` objects whose name begins with
  475. `"set"` called in fulfilling those `rotate` calls?
  476. ____
  477. Such questions may be difficult to express using standard profiling or
  478. logging tools.
  479. [[pre-and-post-conditions]]
  480. === Pre- and Post-Conditions
  481. Many programmers use the "Design by Contract" style popularized by
  482. Bertand Meyer in Object-Oriented Software Construction, 2/e. In this
  483. style of programming, explicit pre-conditions test that callers of a
  484. method call it properly and explicit post-conditions test that methods
  485. properly do the work they are supposed to.
  486. AspectJ makes it possible to implement pre- and post-condition testing
  487. in modular form. For example, this code
  488. [source, java]
  489. ....
  490. aspect PointBoundsChecking {
  491. pointcut setX(int x):
  492. (call(void FigureElement.setXY(int, int)) && args(x, *))
  493. || (call(void Point.setX(int)) && args(x));
  494. pointcut setY(int y):
  495. (call(void FigureElement.setXY(int, int)) && args(*, y))
  496. || (call(void Point.setY(int)) && args(y));
  497. before(int x): setX(x) {
  498. if ( x < MIN_X || x > MAX_X )
  499. throw new IllegalArgumentException("x is out of bounds.");
  500. }
  501. before(int y): setY(y) {
  502. if ( y < MIN_Y || y > MAX_Y )
  503. throw new IllegalArgumentException("y is out of bounds.");
  504. }
  505. }
  506. ....
  507. implements the bounds checking aspect of pre-condition testing for
  508. operations that move points. Notice that the `setX` pointcut refers to
  509. all the operations that can set a Point's `x` coordinate; this includes
  510. the `setX` method, as well as half of the `setXY` method. In this sense
  511. the `setX` pointcut can be seen as involving very fine-grained
  512. crosscutting - it names the the `setX` method and half of the `setXY`
  513. method.
  514. Even though pre- and post-condition testing aspects can often be used
  515. only during testing, in some cases developers may wish to include them
  516. in the production build as well. Again, because AspectJ makes it
  517. possible to modularize these crosscutting concerns cleanly, it gives
  518. developers good control over this decision.
  519. === Contract Enforcement
  520. The property-based crosscutting mechanisms can be very useful in
  521. defining more sophisticated contract enforcement. One very powerful use
  522. of these mechanisms is to identify method calls that, in a correct
  523. program, should not exist. For example, the following aspect enforces
  524. the constraint that only the well-known factory methods can add an
  525. element to the registry of figure elements. Enforcing this constraint
  526. ensures that no figure element is added to the registry more than once.
  527. [source, java]
  528. ....
  529. aspect RegistrationProtection {
  530. pointcut register(): call(void Registry.register(FigureElement));
  531. pointcut canRegister(): withincode(static * FigureElement.make*(..));
  532. before(): register() && !canRegister() {
  533. throw new IllegalAccessException("Illegal call " + thisJoinPoint);
  534. }
  535. }
  536. ....
  537. This aspect uses the withincode primitive pointcut to denote all join
  538. points that occur within the body of the factory methods on
  539. `FigureElement` (the methods with names that begin with "`make`"). This
  540. is a property-based pointcut because it identifies join points based not
  541. on their signature, but rather on the property that they occur
  542. specifically within the code of another method. The before advice
  543. declaration effectively says signal an error for any calls to register
  544. that are not within the factory methods.
  545. This advice throws a runtime exception at certain join points, but
  546. AspectJ can do better. Using the `declare error` form, we can have the
  547. _compiler_ signal the error.
  548. [source, java]
  549. ....
  550. aspect RegistrationProtection {
  551. pointcut register(): call(void Registry.register(FigureElement));
  552. pointcut canRegister(): withincode(static * FigureElement.make*(..));
  553. declare error: register() && !canRegister(): "Illegal call"
  554. }
  555. ....
  556. When using this aspect, it is impossible for the compiler to compile
  557. programs with these illegal calls. This early detection is not always
  558. possible. In this case, since we depend only on static information (the
  559. `withincode` pointcut picks out join points totally based on their code,
  560. and the `call` pointcut here picks out join points statically). Other
  561. enforcement, such as the precondition enforcement, above, does require
  562. dynamic information such as the runtime value of parameters.
  563. === Configuration Management
  564. Configuration management for aspects can be handled using a variety of
  565. make-file like techniques. To work with optional aspects, the programmer
  566. can simply define their make files to either include the aspect in the
  567. call to the AspectJ compiler or not, as desired.
  568. Developers who want to be certain that no aspects are included in the
  569. production build can do so by configuring their make files so that they
  570. use a traditional Java compiler for production builds. To make it easy
  571. to write such make files, the AspectJ compiler has a command-line
  572. interface that is consistent with ordinary Java compilers.
  573. [[starting-production]]
  574. == Production Aspects
  575. This section presents examples of aspects that are inherently intended
  576. to be included in the production builds of an application. Production
  577. aspects tend to add functionality to an application rather than merely
  578. adding more visibility of the internals of a program. Again, we begin
  579. with name-based aspects and follow with property-based aspects.
  580. Name-based production aspects tend to affect only a small number of
  581. methods. For this reason, they are a good next step for projects
  582. adopting AspectJ. But even though they tend to be small and simple, they
  583. can often have a significant effect in terms of making the program
  584. easier to understand and maintain.
  585. === Change Monitoring
  586. The first example production aspect shows how one might implement some
  587. simple functionality where it is problematic to try and do it
  588. explicitly. It supports the code that refreshes the display. The role of
  589. the aspect is to maintain a dirty bit indicating whether or not an
  590. object has moved since the last time the display was refreshed.
  591. Implementing this functionality as an aspect is straightforward. The
  592. `testAndClear` method is called by the display code to find out whether
  593. a figure element has moved recently. This method returns the current
  594. state of the dirty flag and resets it to false. The pointcut `move`
  595. captures all the method calls that can move a figure element. The after
  596. advice on `move` sets the dirty flag whenever an object moves.
  597. [source, java]
  598. ....
  599. aspect MoveTracking {
  600. private static boolean dirty = false;
  601. public static boolean testAndClear() {
  602. boolean result = dirty;
  603. dirty = false;
  604. return result;
  605. }
  606. pointcut move():
  607. call(void FigureElement.setXY(int, int)) ||
  608. call(void Line.setP1(Point)) ||
  609. call(void Line.setP2(Point)) ||
  610. call(void Point.setX(int)) ||
  611. call(void Point.setY(int));
  612. after() returning: move() {
  613. dirty = true;
  614. }
  615. }
  616. ....
  617. Even this simple example serves to illustrate some of the important
  618. benefits of using AspectJ in production code. Consider implementing this
  619. functionality with ordinary Java: there would likely be a helper class
  620. that contained the `dirty` flag, the `testAndClear` method, as well as a
  621. `setFlag` method. Each of the methods that could move a figure element
  622. would include a call to the `setFlag` method. Those calls, or rather the
  623. concept that those calls should happen at each move operation, are the
  624. crosscutting concern in this case.
  625. The AspectJ implementation has several advantages over the standard
  626. implementation:
  627. _The structure of the crosscutting concern is captured explicitly._ The
  628. moves pointcut clearly states all the methods involved, so the
  629. programmer reading the code sees not just individual calls to `setFlag`,
  630. but instead sees the real structure of the code. The IDE support
  631. included with AspectJ automatically reminds the programmer that this
  632. aspect advises each of the methods involved. The IDE support also
  633. provides commands to jump to the advice from the method and vice-versa.
  634. _Evolution is easier._ If, for example, the aspect needs to be revised
  635. to record not just that some figure element moved, but rather to record
  636. exactly which figure elements moved, the change would be entirely local
  637. to the aspect. The pointcut would be updated to expose the object being
  638. moved, and the advice would be updated to record that object. The paper
  639. An Overview of AspectJ (available linked off of the AspectJ web site --
  640. https://eclipse.org/aspectj[]), presented at ECOOP 2001, presents a
  641. detailed discussion of various ways this aspect could be expected to
  642. evolve.
  643. _The functionality is easy to plug in and out._ Just as with development
  644. aspects, production aspects may need to be removed from the system,
  645. either because the functionality is no longer needed at all, or because
  646. it is not needed in certain configurations of a system. Because the
  647. functionality is modularized in a single aspect this is easy to do.
  648. _The implementation is more stable._ If, for example, the programmer
  649. adds a subclass of `Line` that overrides the existing methods, this
  650. advice in this aspect will still apply. In the ordinary Java
  651. implementation the programmer would have to remember to add the call to
  652. `setFlag` in the new overriding method. This benefit is often even more
  653. compelling for property-based aspects (see the section
  654. xref:#starting-production-consistentBehavior[Providing Consistent
  655. Behavior]).
  656. === Context Passing
  657. The crosscutting structure of context passing can be a significant
  658. source of complexity in Java programs. Consider implementing
  659. functionality that would allow a client of the figure editor (a program
  660. client rather than a human) to set the color of any figure elements that
  661. are created. Typically this requires passing a color, or a color
  662. factory, from the client, down through the calls that lead to the figure
  663. element factory. All programmers are familiar with the inconvenience of
  664. adding a first argument to a number of methods just to pass this kind of
  665. context information.
  666. Using AspectJ, this kind of context passing can be implemented in a
  667. modular way. The following code adds after advice that runs only when
  668. the factory methods of `Figure` are called in the control flow of a
  669. method on a `ColorControllingClient`.
  670. [source, java]
  671. ....
  672. aspect ColorControl {
  673. pointcut CCClientCflow(ColorControllingClient client):
  674. cflow(call(* * (..)) && target(client));
  675. pointcut make(): call(FigureElement Figure.make*(..));
  676. after (ColorControllingClient c) returning (FigureElement fe):
  677. make() && CCClientCflow(c)
  678. {
  679. fe.setColor(c.colorFor(fe));
  680. }
  681. }
  682. ....
  683. This aspect affects only a small number of methods, but note that the
  684. non-AOP implementation of this functionality might require editing many
  685. more methods, specifically, all the methods in the control flow from the
  686. client to the factory. This is a benefit common to many property-based
  687. aspects while the aspect is short and affects only a modest number of
  688. benefits, the complexity the aspect saves is potentially much larger.
  689. [[starting-production-consistentBehavior]]
  690. === Providing Consistent Behavior
  691. This example shows how a property-based aspect can be used to provide
  692. consistent handling of functionality across a large set of operations.
  693. This aspect ensures that all public methods of the `com.bigboxco`
  694. package log any Errors they throw to their caller (in Java, an Error is
  695. like an Exception, but it indicates that something really bad and
  696. usually unrecoverable has happened). The `publicMethodCall` pointcut
  697. captures the public method calls of the package, and the after advice
  698. runs whenever one of those calls throws an Error. The advice logs that
  699. Error and then the throw resumes.
  700. [source, java]
  701. ....
  702. aspect PublicErrorLogging {
  703. Log log = new Log();
  704. pointcut publicMethodCall():
  705. call(public * com.bigboxco.*.*(..));
  706. after() throwing (Error e): publicMethodCall() {
  707. log.write(e);
  708. }
  709. }
  710. ....
  711. In some cases this aspect can log an exception twice. This happens if
  712. code inside the `com.bigboxco` package itself calls a public method of
  713. the package. In that case this code will log the error at both the
  714. outermost call into the `com.bigboxco` package and the re-entrant call.
  715. The `cflow` primitive pointcut can be used in a nice way to exclude
  716. these re-entrant calls:
  717. [source, java]
  718. ....
  719. after() throwing (Error e):
  720. publicMethodCall() && !cflow(publicMethodCall())
  721. {
  722. log.write(e);
  723. }
  724. ....
  725. The following aspect is taken from work on the AspectJ compiler. The
  726. aspect advises about 35 methods in the `JavaParser` class. The
  727. individual methods handle each of the different kinds of elements that
  728. must be parsed. They have names like `parseMethodDec`, `parseThrows`,
  729. and `parseExpr`.
  730. [source, java]
  731. ....
  732. aspect ContextFilling {
  733. pointcut parse(JavaParser jp):
  734. call(* JavaParser.parse*(..))
  735. && target(jp)
  736. && !call(Stmt parseVarDec(boolean)); // var decs are tricky
  737. around(JavaParser jp) returns ASTObject: parse(jp) {
  738. Token beginToken = jp.peekToken();
  739. ASTObject ret = proceed(jp);
  740. if (ret != null) jp.addContext(ret, beginToken);
  741. return ret;
  742. }
  743. }
  744. ....
  745. This example exhibits a property found in many aspects with large
  746. property-based pointcuts. In addition to a general property based
  747. pattern `call(* JavaParser.parse*(..))` it includes an exception to the
  748. pattern `!call(Stmt parseVarDec(boolean))`. The exclusion of `parseVarDec` happens
  749. because the parsing of variable declarations in Java is too complex to
  750. fit with the clean pattern of the other `parse*` methods. Even with the
  751. explicit exclusion this aspect is a clear expression of a clean
  752. crosscutting modularity. Namely that all `parse*` methods that return
  753. `ASTObjects`, except for `parseVarDec` share a common behavior for
  754. establishing the parse context of their result.
  755. The process of writing an aspect with a large property-based pointcut,
  756. and of developing the appropriate exceptions can clarify the structure
  757. of the system. This is especially true, as in this case, when
  758. refactoring existing code to use aspects. When we first looked at the
  759. code for this aspect, we were able to use the IDE support provided in
  760. AJDE for JBuilder to see what methods the aspect was advising compared
  761. to our manual coding. We quickly discovered that there were a dozen
  762. places where the aspect advice was in effect but we had not manually
  763. inserted the required functionality. Two of these were bugs in our prior
  764. non-AOP implementation of the parser. The other ten were needless
  765. performance optimizations. So, here, refactoring the code to express the
  766. crosscutting structure of the aspect explicitly made the code more
  767. concise and eliminated latent bugs.
  768. [[starting-conclusion]]
  769. == Conclusion
  770. AspectJ is a simple and practical aspect-oriented extension to Java.
  771. With just a few new constructs, AspectJ provides support for modular
  772. implementation of a range of crosscutting concerns.
  773. Adoption of AspectJ into an existing Java development project can be a
  774. straightforward and incremental task. One path is to begin by using only
  775. development aspects, going on to using production aspects and then
  776. reusable aspects after building up experience with AspectJ. Adoption can
  777. follow other paths as well. For example, some developers will benefit
  778. from using production aspects right away. Others may be able to write
  779. clean reusable aspects almost right away.
  780. AspectJ enables both name-based and property based crosscutting. Aspects
  781. that use name-based crosscutting tend to affect a small number of other
  782. classes. But despite their small scale, they can often eliminate
  783. significant complexity compared to an ordinary Java implementation.
  784. Aspects that use property-based crosscutting can have small or large
  785. scale.
  786. Using AspectJ results in clean well-modularized implementations of
  787. crosscutting concerns. When written as an AspectJ aspect the structure
  788. of a crosscutting concern is explicit and easy to understand. Aspects
  789. are also highly modular, making it possible to develop plug-and-play
  790. implementations of crosscutting functionality.
  791. AspectJ provides more functionality than was covered by this short
  792. introduction. The next chapter, xref:language.adoc#language[The AspectJ Language], covers in detail
  793. more of the features of the AspectJ language. The following chapter,
  794. xref:examples.adoc#examples[Examples], then presents some carefully chosen examples that
  795. show you how AspectJ might be used. We recommend that you read the next
  796. two chapters carefully before deciding to adopt AspectJ into a project.