Slashdot Mirror


Aspect-Oriented Programming with AspectJ

Verity Stob writes "There is a turning point in the emergence of a programming methodology. It doesn't matter how big and popular the website is, nor how many papers have been published in the ACM journals or development magazines, nor even whether the first conferences have been a sell-out. A methodology hasn't made really made it until somebody has published a Proper Book. With Aspect-Oriented Programming with AspectJ author Ivan Kiselev is bidding to drag AOP into the mainstream. He is motivated, he says in his introduction, by the recollection of the 25 odd years it took for the object-oriented concept to spread from its Simula origins in frosty Norway to being the everyday tool of Joe Coder. He aims to prevent this delay happening to AOP." Read on for Verity Stob's review of Kiselev's book. Aspect-Oriented Programming with AspectJ author Ivan Kiselev pages 274 publisher SAMS rating Excellent reviewer Verity Stob ISBN 0672324105 summary Introduction to a new programming technique using an extension to Java

He has divided the book into four parts. Part I provides a brief sketch of AOP and introduces its concepts. AOP builds on OOP, asserting that we need a new programming entity called, wait for it, an aspect. Mr Kiselev's explanation of aspects reminded me of that bit in The Hitchhiker's Guide to the Galaxy when the planet Golgafrincham divided its population into A types (who were the leaders, the scientists and the great artists), the C types (who were the people who did all the actual making of things and doing of things), and the B types, who comprised everybody left over: telephone sanitizers, advertising account executives and hairdressers. As I understand Mr Kiselev, the AOP view of things is that objects and classes (A type thinkers) and low-level procedures and APIs (C type doers) can be nicely encapsulated using traditional components. But aspects, software's little hairdressers, get their fingers into everything, and until now there has been no way to encapsulate them. This of course is what AOP in general and specifically the AspectJ superset of the Java language set out to do.

AspectJ's eponymous aspects are constructs not unlike ordinary classes. Mr Kiselev has not resisted the temptation to make an aspect Hello World example, and it looks reassuringly so-whatish:

package intro;

import java.io.*;

public aspect HelloWorldA
{
public static void main(String args[])
{
System.out.println(Hello, world!);
}
}

Mr Kiselev then lays out his stall of New Things. A join point is any point in execution flow that AspectJ can identify and -- to get slightly ahead of ourselves -- execute some extra code. The most frequently used kind of join point being the call to a method. Pointcuts specify collections of join points; as a regular expression is to an instance of matched text, so a pointcut is to a matching join point. An advice (with horrid plural 'advices') is the code to be executed when a given pointcut is matched. If you are familiar with Eiffel's pre- and post-conditions, then you'll understand if I say that it is common for advices to run in the same way, topping and/or tailing the execution of a method. The differences are that aspects are specified from outside the method without touching the method or its class's code, and that aspects can be applied to multiple methods in one go. Mr Kiselev concludes this section of the book with a few simplistic examples of 'here is class A, here is class B' kind.

In Part II Mr Kiselev rolls up his sleeves and takes us through an extended, realistic example. I did wonder if perhaps it weren't a wee bit too realistic, as it is a miniature website application for news story submission and reading -- sort of Slashdot Ultralite -- all done using JSP and a MySQL database. Just explaining this setup, without even using any AspectJ, consumes a 15-page chapter. Since I am a C++ programmer who has not had any contact with JSP, I was initially anxious that I might not be able to follow this. However, recalling that www.[name withheld].com, the clumsiest, ugliest corporate website on the Internet, is programmed in JSP, I reasoned that if the dolts that programmed that site could understand JSP then it couldn't be very hard. So it proved.

The first example comprises adding password protection to the application. This is achieved by adding an advice that intercepts calls to doStartTag() methods. The advice can test if the user is logged in and, if he isn't, throw an exception that will dump him back at the login page. (Who says exceptions aren't 21st century gotos?) At this point Mr Kiselev admits that the cute 10-line implementation that he initially shows is in reality a non-starter; for one thing not all pages that must be secured define doStartTag() methods, for another the aspect can't reach an instance variable it needs to read because it is declared in protected scope. The second problem is easily overcome. AOP offers a mechanism by which extra classes can be bodged ('introduced' is the preferred verb in the AOP community) into the hierarchy as parents of existing classes. He uses this to add an accessor method for the field in question. The other problem is not so neatly smothered, and it is somewhat ruefully that Mr Kiselev produces his final, two-page solution. But I think that it is greatly to Mr K's credit that he does this - it tastes like programming in the real world as I have experienced it.

For the rest of Part II, Mr K demonstrates other applications of AOP using the AspectNews code. This includes Eiffelish design-by-contract stuff, improved exception handling, various debugging and tuning techniques (specifically logging, tracing and profiling) and a chapter on runtime improvements - stream buffering, database connection pooling and result caching - which show the AOP way to do things, usually where I would expect to be putting in proxy classes.

In part III we get down and dirty with the AspectJ language. This is the part where the book explains the obscure stuff: how to make a pointcut that picks up object preinitialization, or make an advice that goes off only when you are exiting a method on the back of an exception. I skimmed this bit - I guess it will become vital when I start using AspectJ in earnest. It looked good and clear on a flick through. A brief part IV contains some patterns, to give one a start when engaging AspectJ in earnest. Apparently it is horribly easy to create infinitely recursive situations, so if you here a faint popping sound from your machine it will be the stack colliding with the heap. There are seven appendices, supplying such things as a summary of the API in AspectJ's packages and hints on obtaining and using the Open Source supplementary tools mentioned in the book (Tomcat JSP container, MySQL database and Ant make replacement). AspectJ itself, now escaped from Xerox PARC, can be downloaded from the Eclipse website.

Complaints? None really. Oh all right, here's a nitpicklette because it's you: at page 75 Mr Kiselev adopts the irritating Internet habit of writing 'loosing' when he means 'losing'. Note to publisher SAMS proofreaders: do I win 25 cents?

For the rest, this is a lucid and readable book that describes the Next Big Methodology. I'm a bit alarmed at the prospect of squeezing new actions into the cracks of existing code, but I dare say I'll grow to love it.

A word of warning to the eager: since this technology is currently implemented as a species of preprocessor that relies on having all the source code available at once, so it is rather slow and probably isn't going into production shops for a while. There again, I seem to remember the comparable Cfront C++ compiler doing rather well, before we had platform-native C++ compilers.

And to the sceptics: if you think you can ignore AOP, don't forget the fate of the A and C type inhabitants of Golgafrincham, who having sent their B type telephone sanitizers into exile were all wiped out by a germ caught from a particularly dirty telephone.

You can purchase Aspect-Oriented Programming with AspectJ from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

22 of 426 comments (clear)

  1. I prefer reading... by borgdows · · Score: 5, Funny

    Microsoft-oriented development book at Microsoft Press!

    This book contains every programming concepts and practices to avoid like hell!

  2. Fascinating by Limburgher · · Score: 4, Funny

    I love that aspects seems to provide alternative techniques without loosing any ease-of-use, coing-wise. I was afraid that in switching to this new method I'd loose some functionality, or maybe loose some speed, but so far so good. Nothing to loose any sleep over. :)P

    --

    You are not the customer.

  3. Yet another reason to switch to Lisp by Anonymous Coward · · Score: 5, Insightful

    I should have stuck with Lisp all this time. When OO became hot, we could switch to OO without a preprocessor (early C++) or a whole new language (C++ or Java). (Eventually, Lisp got CLOS -- the first standard language to do OO, in fact.) If AOP gets hot, that'll just be a few more macros.

    Once you've used a language like Lisp with closures, macros (at the language level, not wimpy C macros), and code-is-data, it's hard to go back. I feel sorry for everybody who has to use Java, for whatever reason, and will have to get a new language/compiler/libraries just to take advantage of a slight change in "what's hot today".

    1. Re:Yet another reason to switch to Lisp by redragon · · Score: 4, Insightful

      And I think it's easier for people to write bad LISP than bad C/C++ (though I could be wrong). It seems to me that LISP suffers from "data morph" issues more than any other language.

      (5 256 "Item" "Description") represents your base data type.

      Programmer A:
      "I don't need that first number..."
      (256 "Item" "Description")

      Programmer B (who get's A's data):
      "What happened to that number?"
      (256 "Item" "Description" 5)

      Programmer C (who get's B's data):
      "Strings? We don't need no stinking strings, we can look those up in a table! I can make that table global! Sweet!"
      (256 1 20 5)

      Person hired 2 years later to fix a bug:
      "What the f*ck?!?"

      It seems to me that Scheme and Lisp over-extended themselves, and are just too powerful/flexible for their own good, and that some "rules" should be in place...

      And as the previous poster said...
      ((((()()))))
      Lisp will make you hate parenthesis.

      C

      --
      - Sighuh?
  4. Bad code by Anonymous Coward · · Score: 4, Funny

    System.out.println(Hello, world!);

    Where are the quotes?
    I dont trust this guy if he cant write a HelloWorld app.

  5. Re:Where's this useful? by Mahrin+Skel · · Score: 4, Informative
    I can see it. Okay, you know how OOP lets you over-ride ancestor behaviour in descendants? But if you want to combine the behaviour of two different objects you have to either encapsulate one in the other, or go all the way back to their common ancestor and create a new descendent line because if you change the root line then *all* descendants are changed?

    AOP would seem to let you over-ride methods or invoke special handling *without* touching the object directly. You simply tell the compiler "When this method is called, do this first (or afterwards)."

    On the one hand, this could lead to spagetti code nightmares, since execution paths could become effectively untraceable. On the other, it's in many ways cleaner than putting your special-case or over-ride code directly into the methods and objects directly.

    --Dave

  6. Re:Where's this useful? by cushty · · Score: 5, Informative

    Aspects are cross-cutting concerns, they are things that cut through numbers of classes. My way of thinking: draw vertical rectangles side-by-side and call these "classes", now draw a horizontal box that cuts through them all and this is an "aspect".

    The simple example, and one used in the book I believe, is that of logging. Say you have to log the entry to and exit from every single method in your code. Typically you would probably write this directly putting "entering XYZ, exitting XYZ" actually in the code. But with aspects you can write one aspect that basically says "on entry to any method log the method and parameters, on exit log the method" and compile your code and away you go.

    So? Why would I want to do this? Well, now that you have been through your development process and discovered everything runs fine, you decide to go into production. Want to remove every single log line to improve speed? With the "normal" approach you'll have to write a script to remove them or do it manually. With aspects: just dont use the aspect in the compilation! Put them back in by compiling in the aspect again.

    For me aspects are a real benefit but they do you head in for a while when you're an OO programmer!

  7. My 2 bits... by praetorian_x · · Score: 5, Insightful

    Aspect oriented programming is moderately useful, though, if it isn't built into the language (and, in java, it isn't) it can be cumbersome to work with.

    In java you can get 50% of the way to AOP using Dynamic Proxies (see java.lang.reflect.Proxy) which allows you to wrap all method invocations or an object. This without an outside tool. This is how a lot of j2ee app servers do thier magic.

    By and large, the more I work in java, and the more I work in Lisp, I realize how lacking java is in dynamic behaviors. The lisp guys yawned when OO became all the rage because, well, it is so easy to do in lisp. If AOP gets big in java, they will yawn at that too:

    "Oh, so functions and try blocks are your boundry block for inserting aspect oriented code? Well, *every parenthisis* is ours. Put that in your JVM and smoke it."

    Cheers,
    prat

    1. Re:My 2 bits... by Fnkmaster · · Score: 4, Insightful


      In java you can get 50% of the way to AOP using Dynamic Proxies (see java.lang.reflect.Proxy) which allows you to wrap all method invocations or an object. This without an outside tool. This is how a lot of j2ee app servers do thier magic.


      Sure, of course you can. AOP is a technique, supported by tools, it doesn't need to be hoodoo magic to be useful. Mind you, like you said, it'll get you 50% of the way. You can get 50% of the benefits of assertions by writing a static Assert class and using it consistently. It's just that it is nice to have capabilities either built into the language to support good practices, or extensions to the language (a la AspectJ) to support them.


      And the List thing is tired. We all know that Java is limited. It's limited compared to C++, it's limited compared to Lisp. Ya know what? That's a good thing. For large software development projects with many engineers involved. I can pick up other people's code and not worry about whether X really means X or whether it's a macro that's been defined elsewhere to mean Y. I realize my view on this isn't the most popular on Slashdot, but that's probably because people haven't had to manage teams of developers who aren't populated throughout with brilliant coders, capable of writing fast, functional readable code in languages that leave n degrees of freedom.


      Adding capabilities to a language to support a particular kind of new programming paradigm is not unreasonable. I realize that the fact an extension to the language is needed seems like a limitation, and it is, but like I said, that limitation can be a godsend, and it's worth the tradeoff.


      Of course, when I'm working on my own time on my own projects, I far prefer to use a manly language like C++, or a pleasant language like Python.

  8. Re:Where's this useful? by nojomofo · · Score: 5, Insightful

    I'm not trying to troll here, but I'm afraid this might sound like it.... It sounds to me like the main selling points of AOP are that you don't have to design things well in the first place, because if you missed something, well then you can change how your objects behave without redesigning them.

    The place where this wouldn't be true is with code that's part of the API or other code that comes packaged. I think that changing the behavior of this type of code sounds pretty dangerous to me - there's a reason that some data is kept in private and protected variables! Wouldn't you get into situations where you've added and aspect or a parent or some such thing, and in the process you access a private variable, and then you upgrade your runtime environment which changes the INTERNAL structure of the code that you hooked into (leaving the external API the same), breaking your code? Isn't that what code encapsulation is for? What I'm hearing touted as AOP's best feature is that you can break encapsulation.... Count me out.

  9. How true by arvindn · · Score: 4, Funny
    It doesn't matter how big and popular the website is.

    Yup. Nothing can save it from slashdot.

  10. Other Aspect Oriented Technologies by Frums · · Score: 4, Informative

    Since AspectJ is getting some attention I figured i would point out some other AOP resources

    • MDSOC - Paper - Is basically IBM's take on AOP. It avoids creating Aspect Space and Object Space (what belongs in an aspect, what in an Object?) but is less mature than AspectJ
    • HyperJ - Home - IBM's Java language stuff supporting MDSOC
    • JAC - Home - Aspect oriented middleware for Java. I haven;t explored this one much, is on my todo list.
    • Aspect Browser - Home- A tool to help identify crosscutting concerns in Java (emacs!)
  11. Workarounds? by mparaz · · Score: 4, Informative
  12. Re:Where's this useful? by Enonu · · Score: 5, Informative

    Yeah, this review didn't introduce AOP that well.

    Going here:
    http://dev.eclipse.org/viewcvs/indextech.cg i/~checkout~/aspectj-home/doc/progguide/index.html

    I found this code example:

    pointcut move(): call(void FigureElement.setXY(int,int)) ||
    call(void Point.setX(int)) ||
    call(void Point.setY(int)) ||
    call(void Line.setP1(Point)) ||
    call(void Line.setP2(Point));

    and then this:

    after(): move() {
    System.out.println("A figure element moved.");
    }

    As you can see, "after" any method call as defined by the pointcut, System.out.println is executed to reflect this fact.

    I can see how this would be great for logging, checking pre/post conditions, quicker debugging, or anything else that is of a "horizontal" nature in your code.

  13. Re:So, what is this? by Minna+Kirai · · Score: 5, Insightful

    I've read a few papers, but never managed to pay much attention. However I tried to put it in terms of how you might accomplish such effects with a traditional programming langauge.

    Basically, imagine if you wrote a program which had "hooks" scattered through it. As you write your code, you place hooks for before/after doing many things: reading user input, transmitting network data, accessing preference files, checking permissions, etc. (Imagine wrapping all your function calls with dynamically-bound functions which you don't yet know if map to an identity function, or have some effect)

    Other parts of the program can then hook into these things and effect how your program runs, without them having to go through and modify your code. (Example: if they want to log a message to file everytime your "CastRay()" function is called, they can do this without going in and editing your code).

    Now, imagine than rather than the programming having to plan ahead to scatter hooks all around his code (uglifying it towards readers who don't care about them), they are inserted automatically by the compiler.

    So a person can create a function which will be automatically called whenever some other set of 3 different functions is called, without having to go modify each one. Instead of going to each function body and adding a call, he at one position attaches his code to functions of that kind. The program is shorter, but has more effects. This may mean, when all goes well, that if someone adds a new function with similar effects, those hooks may still get called.

    Now, is all this a code idea? It's hard to say, Aspect-Oriented programming (like OO programming) is yet another way for a program to do things without the source code making it abundantly clear. In OO, if you see one method A call method B, you must check the source code for all base classes to see if and how B was virtually overridden, a complexity that didn't exist before. Now, with AOP, you must be aware "is this behavior creating a context which will cause some Aspect to add in more effects"?

    In both those cases, the program is doing things that the source code doesn't make 100% clear to a programmer reading a single function body. This can be either good or bad. The usage of editing tools which evaluate the code and alert the reader to these facts (analogous to "class browsers" in several IDEs) shift it much further towards "good".

  14. Re:So, what is this? by tickleboy2 · · Score: 5, Insightful

    Aspect Oriented programming is a brand new programming paradign, kinda of like the switch you made when going from functional programming to object oriented programming. It's a different way of expressing your programs

    The reason that Aspect Oriented Programming was created was due to "cross-cutting" concerns that cannot be easily modelled in object oriented programming. I read the presentation for AspectJ and the example they used was logging in Apache Tomcat. Bascially the code that is used for logging is scattered throughout the whole program on hundreads of different lines, not all in one nice neat class. Aspect Oriented Programming wants to give the programmer the tools to gather all of this code together.

    Bascially, Aspect Oriented Programming is supposed to result in: less tangled code (code that is fragmented throughout your program because you are unable to modularize it well), more natural code, shorter code, easier to maintain and evolve, and more reusability.

    One question I had about the book that the review didn't seem to answer was did the book talk at all about designing using Aspect Oriented Programming? Just like Object Oriented Programming, it's a great tool until you get some inexperienced programmer who just knows how to program functionally, and thus doesn't use the advantages of aspect oriented programming. I too would like to learn more about how to go about designing a program in an Aspect Oriented way; such as how to identify aspects, what are some common aspects, etc.

    In all, I'm very excited about Aspect Oriented programming. I think it has the ability to allow programming to shape thier programs more naturally, make their programs easier to understand, and make the whole process much eaiser. But of course as with any new technology, it has some growth and refinement to go through yet.

    Those of you who would like more information can check out the AspectJ webpage, or the Aspect Oriented Software Design webpage.

    --
    The only thing that will stop you from fulfilling your dreams is you. - Tom Bradley
  15. disgusting by rpeppe · · Score: 5, Insightful
    Sounds like a disgusting way of trying to legitimise hacks to me. Changing code in ways it wasn't meant to be changed, guaranteed to break lots of things (hence the "horribly easy to accidentally create infinite recursion" reference... no shit Sherlock!)

    When will people realise that the most important thing in a programming language is to make it possible to reason about one part of it independent of another part? Most of the time spent developing a program is spent modifying code, not creating new code!

    Unfortunately people don't realise this: they just want a way of hacking something existing into something different, cross their fingers and hope that it works when someone changes some other part of the system.

    Sadly, it's not just AOP: some of the "usual" OO programming language features suffer this kind of problem too.

    Then again, maybe I'm completely wrong, and AOP has a sound theoretical basis and has been created by someone with deep understanding of programming language developments over the last thirty years... someone please reassure me!

  16. My take on AOP... by Fnkmaster · · Score: 4, Insightful
    I checked this out almost a year ago now, and I'm sure it's come a way since then. First off, AOP is not going to replace OOP or any other paradigm of programming. It simply provides a viable alternative way to think about the control flow and execution of a program, and a shortcut for making more maintainable code.


    Anybody who has worked extensively in Java has found this problem before. Cross-cutting concerns - you know, those systemic things that infiltrate their way into every module of your humongo-system, no matter how you try to partition it. Now, object-oriented programming, isn't that supposed to let you "blackbox" things so you can just abstract away such things and throw them in some "common" or "system" package and be done with it? Sure, you can. And you probably have. And I've done it too.


    But these solutions can be suboptimal - for example, a project I once worked on had an Interface in the com.blah.blah.system package for logging, messaging, persistence, and some other features. These were always nasty pains in the ass to manage. I mean, some implementor of these objects existed everywhere in the system - if something changed fundamentally, or there was some insuffiency in the interface that was discovered, god forbid, you'd have to root around for hours changing code everywhere. Especially when exception signatures changed. Which eventually leads, in sheer frustration, to using Runtime exceptions everywhere, or declaring all of your "system" interfaces with "throws Exception". Ugh. Each solution seems worse than the problem.


    Admittedly, problems like this can be solved with good refactoring tools and practices. But not always well. The exception issue for "system" or "cross-cutting" interfaces was one I've never seen solved well (again, I'm thinking of Java here, it's the language I have the most experience working in large commercial-scale projects in where this stuff is really important). If you are working on medium or small sized open source projects, or medium or small sized tools or desktop applications, you may never have come across these kinds of limitations or frustrations in sufficient numbers to justify looking into AspectJ/AOSD in general. But if you've worked on large enterprise software projects, I'm sure you can see that there is a need to "patch," but certainly not replace, the standard OOP methodology to address these kinds of concerns.

  17. Re:So, what is this? by Caoch93 · · Score: 5, Interesting
    Now, is all this a code idea? It's hard to say, Aspect-Oriented programming (like OO programming) is yet another way for a program to do things without the source code making it abundantly clear. In OO, if you see one method A call method B, you must check the source code for all base classes to see if and how B was virtually overridden, a complexity that didn't exist before. Now, with AOP, you must be aware "is this behavior creating a context which will cause some Aspect to add in more effects"?

    It's my opinion that, if you have to ask that question, then you and everyone else on your team are doing AOP in a bad way. The entire function of AOP is to separate disjoint concerns so that you don't think about them when you're programming. You write application logic. Your fellow team member maintains your security aspect. You don't ask "When I call this method, will it trigger the security aspect?". Especially in a world of runtime AOP, it's not possible for you to really have a reliable answer.

    Long story short- if two separated concerns in AOP have such a sufficient dependency that you have to ask yourself a question like that, then they should not be separate concerns at all. At least, in my opinion.

  18. Re:Where's this useful? by MsWillow · · Score: 4, Informative

    Want to remove every single log line to improve speed? With the "normal" approach you'll have to write a script to remove them or do it manually.

    Or you change one #define in one .h file, re-compile and you're golden. That removes all the #ifdef debug code you put in when you were writing it.

    Do they teach programmers anything useful these days? Sheesh.

    --

    Lemon curry?
  19. Overlooked extensions to C by WebfishUK · · Score: 5, Funny



    Instead of looking for radically new approaches in computer language development why doesn't someone introduce more colour into standard C. For instance we have if and while, how about adding verbs such as when, where or how.

    Taking it further we might like to introduce more polite language into code such WouldYouBeSoKindAsTo or WhenYouAreReady. Imagine the code you could write...

    when (time == "morning")
    WouldYouBeSoKindAsTo (turn_on_alarm);


    Alternatively we could convert C from English into, say, German. So if would become wenn etc. You could even mix nationalities. For instance if you wanted to be very forceful about a particular if statement you could use the German. If you wanted to seduce the code you might use the French.

    Come on all it takes is some imagination. (Alternatively we could all just start using befunge!)

    --
    -- "Can't sleep, clowns will eat me!"
  20. Hidden Horror Show by piobair · · Score: 4, Insightful

    I took a look at AspectJ awhile ago and instantly spotted the hidden horror show for implementation: There is no test you can write to assure your aspect was applied appropriately. (at least there wasn't when I looked). Apparently nobody sees this as an issue? The application of aspects is essentially a blind process before compilation occurs. The best you can do is place errors in your aspect and break the compile. I can't imagine turning this tool loose on a development organization.

    --
    I have a second sig, I call it sig#2.