Aspect Oriented Programming: The future?

Discussions

News: Aspect Oriented Programming: The future?

  1. Aspect Oriented Programming: The future? (61 messages)

    Aspect Oriented Programming (AOP) is getting a head of steam recently. If you are interested in learning how to help with "cross-cutting concerns" and the new wave that represents the same bridge as OOP was from procedural, check out the technology, and this introductional article:

    http://www.javaworld.com/javaworld/jw-01-2002/jw-0118-aspect.html.

    How many developers are playing with AOP?
    How many developers are using it in production systems?
    Is AOP going to be the new paradigm shift in the industry?

    Threaded Messages (61)

  2. How many developers are playing with AOP?


    I am. It simplifies things quite a bit.

    > How many developers are using it in production systems?

    Not yet.

    > Is AOP going to be the new paradigm shift in the industry?

    I think and hope so. It'll probably take awhile until the concepts and tools have been simplified and tested enough though.

    /Rickard
  3. I have been reading up the introductory article on AOP and im still struggling to come to grips with some of the concepts to quote from the article:
    "AOP differs most from OOP in the way it addresses crosscutting concerns. With AOP, each concern's implementation remains unaware that other concerns are "aspecting" it. That represents a powerful paradigm shift from OOP".What exactly is implied by cross cutting concerns..and how is it a paradigm shift from OOP?
  4. "Implying a paradigm shift from OOP" doesn't mean AOP stands in competition to OOP. In fact, the two are quite orthogonal. An example of crosscutting concerns would be logging code that is in every one of your classes. The logging is a crosscutting concern because it is duplicated across your application. You can refactor it into a framework method, write_log() so that all the other classes just call this method, but write_log() is still all over your code. Aspects allow you to completely remove write_log() from your code and refactor it into an aspect. When you run your build with the aspect compiler, write_log() will be added to the compiled code, but you don't have to deal with it.
  5. Aspect Oriented Programming: The future?[ Go to top ]

    From the EJB perspective, I think the future of declarative technologies will turn in the Aspect-Oriented direction. With AOP, you can plug and play any service you want to into a container. E.G., if you don't like your container vendors persistence service, you can get someone else's and use that. Another point for AOP is that the aspect generated code is woven into the container code. So you or your vendors write the aspects and at runtime you have a single optimized unit of service and "container". It's not like there's some container module intercepting calls then delegating them off - at runtime this overhead is removed these subsystems can be directly intermingled.
  6. Aspect Oriented Programming: The future?[ Go to top ]

    From the EJB perspective, I think the future of declarative

    >technologies will turn in the Aspect-Oriented direction.

    I can only agree.

    > With
    >AOP, you can plug and play any service you want to into a
    >container. E.G., if you don't like your container vendors
    >persistence service, you can get someone else's and use that.

    And you can also *remove* it altogether if you don't need it. Include what you use, remove what you don't use. Great.

    >Another point for AOP is that the aspect generated code is
    >woven into the container code.

    That depends on the implementation. See my blog at dreambean.com for a description of an alternative one (I assume you're talking about AspectJ). AspectJ isn't that great for enterprise type systems with loads of objects.

    > So you or your vendors write
    >the aspects and at runtime you have a single optimized unit of
    > service and "container". It's not like there's some container
    > module intercepting calls then delegating them off - at
    >runtime this overhead is removed these subsystems can be
    >directly intermingled.

    I've been working on an AOP implementation that actually uses dynamic proxies and delegation, and while there is a performance penalty, it also scales better (same principle as with EntityBeans, with the proxy/instance separation). With a non-weaving solution you can also get other benefits, such as loading only those parts of an object that is actually used. You can't do that with a weaving solution since you'll always have the entire "instance" (=combination of all extensions) in memory. It's also way trickier to do lazy-loading and soft referencing of other objects, i.e. you get the whole object model in-memory which is BAD.


  7. Aspect Oriented Programming: The future?[ Go to top ]

    I'm not sure I'd analogize the shift from OO to AO with the shift from procedural to OO.
  8. Aspect Oriented Programming: The future?[ Go to top ]

    I agree, it's bigger.

    ;-)

    The difference, to me, is that it's an exponential curve and the further you get on it, the bigger the next step becomes. This is going to be a huge leap.

    /R
  9. It will be a big shift. It will just take awhile for everyone to get upto speed.

    I wonder if we will see native support for aspects in the JVM in the medium-term.

  10. Yes it will take awhile, since it's a huge shift in terms of mindset. Which is why EJB is important, because it's a step in that direction, due to declarative security and tx's (miniscule points, granted, but still in the right direction).

    What kind of native support would be necessary? Are you talking about language changes as well, for example as those in AspectJ?
  11. Aspect Oriented Programming: The future?[ Go to top ]

    Hi there.

    I've been playing around with AspectJ for about a year, I agree it is a great paradigm shift - though often a little slippery to conceptualize when you are used to the 'traditional' methods. It's true EJB does take us in the right direction in a practical sense - but does not begin to address the enormous change in viewpoint that is necessary to take an AO view of a system.

    I'd be interested to know what sort of practical applications/area that you have found for AOP, apart from the ones that are always mentioned, i.e. logging, authentication, transations etc. I find that the methodology works well for these system level services - but I have yet to 'cleanly' abstract any higher level aspects.

    Also how do you find the traditonal values of OOP apply to AOP? For instance data/functionality encapsulation becomes a less clean cut issue when you can merge in any new data/methods etc.


  12. Aspect Oriented Programming: The future?[ Go to top ]

    I think there is an obvious fit for instrumenting code. I think it offers an alternative to dynamic proxies that is much more powerful. At a higher level, it allows you to easily weave code together that would otherwise be difficult or time consuming which will lead to new patterns and behavior.

    -Matt
  13. "I think there is an obvious fit for instrumenting code. I think it offers an alternative to dynamic proxies that is much more powerful."

    Matt, this where we are aiming for with Jiapi project. It can be used to implement crosscutting concerns at bytecode level.
    I tend to believe that the difference with AOP (e.g AspectJ) is that our focus is in deployment and linking whereas AOP is an integral part of your development process. For instance, a container which deploys an application can't easily utilize a traditional AOP tool since they usually require the sources to be avaliable. If the instrumentation is done at a bytecode level, it is possible to add crosscutting concerns at load/link time.
  14. The AspectJ language was designed to support weaving at many different times: compile, load, or even run-time in the JVM. Weaving into bytecodes at both compile and load-time will definately be provided in a future release. This will allow weaving at compile-time into libraries for which source code is not availabe. It will also support aspect-aware ClassLoaders that can perform weaving at load time on arbitrary classes. One advantage of a language like AspectJ, rather than an explicit meta-tool like jiapi, is that it separates the specification of a crosscutting concern from any particular implementation strategy for weaving.

    Note: we see the value of these meta-tools for implementing a given weaving strategy. We are looking at several existing meta-tools to simplify the process of bytecode weaving. The current front-runner for us is bcel.

    The reason that bytecode weaving is not available today is that we've focussed our development resources on language issues. For many years programmers have been using meta-programming techniques to better capture crosscutting concerns. These techniques are very powerful; however, by working at the meta-level they typically sacrifice some of the good software engineering properties of a base-level language. AspectJ provides a language that can cleanly capture crosscutting concerns while preserving the static type checking, modularity, and composability of Java.
  15. In the Enterprise Java area, I think compiler integration would be a big plus. If ajc were integrated into javac or an ejbc then many objections I have heard to AspectJ would disappear.
  16. Thanks for posting your comments Jim.
    Since you are "in the know", have you seen the use of AOP (and AspectJ) growing in the industry? Are a lot of people taking the step from "playing with it" to using it in production.

    Keep up the great work on AspectJ (and JPython wasn't bad either ;)
  17. I think that AOP + OOP will be future. In this case some patterns (interseptor, visitor) will become obsolete.
    And there will be no shift from OOP to AOP beacause AOP it's just add-on to existing programming paradigms.
  18. Uses for Aspect Oriented Programming[ Go to top ]

    Luke Studley writes:
    >I'd be interested to know what sort of practical applications/area that you
    >have found for AOP, apart from the ones that are always mentioned, i.e.
    >logging, authentication, transations (sic)

    One of the nice properties of using AspectJ is its adoption curve. One can use unpluggable aspects like tracing and debugging output to help with development without requiring production use. There are a series of increasingly valuable production applications as one uses it more extensively.

    Here is a sampling of some AspectJ uses we're seeing industry interest in:

    1. Testing:
    - failure injection (e.g., testing the affect of a network failure by throwing an exception while a method runs)
    - white box testing (e.g., checking a private member variable against an expected result)
    - regression testing (e.g., automatically capturing values at all join points in a test run)
    2. Quality management:
    - error handling (e.g., converting exceptions thrown to an EJB client from CMT enterprise beans to distinguish transaction aborted, programming errors, and resource failures)
    - self-monitoring (and remediation): systematically observing for abnormal conditions and responding (e.g., first failure data capture)
    - standards enforcement (e.g., only allowing factory methods to invoke a constructor, ensuring data access is done by a helper class and not directly within EJBs)
    3. Crosscutting Functionality:
    - Metadata management. E.g., systematically updating fields such as date last modified, user last modifying, object identity, etc. Using superclasses to handle this runs into problems when changing which entities have what metadata, and because every method has to explicitly call super.operation(args)
    - Optimistic concurrency control. This requires specialized metadata management and consistent enforcement of semantics.
    - Metering: tracking the use of functions for billing or quality of service measurements.
    - Context-sensitive state management. E.g., checking the key of objects being edited (to avoid bugs from back buttons)

    Context-sensitivity is especially powerful when one functionality that depends on multiple concerns. For example, detecting errors, measuring performance or personalizing information based on the type of operation in progress. Interceptors, specialized design by contract tools, etc. do not give you the same kind of integrated power.

    4. Feature Management:
    - unpluggable features. Using aspects to integrate the changes to many classes required to support an optional feature. The aspects will often delegate work to implementation clases.

    Ron
  19. I read an article in the academic realm (awhile ago) where some professors were hacking on a JVM that did JIT weaving. They claimed good performance, and yes... the language changes were built into the JVM

    EJB is a good step. Sometimes I feel that it is kinda procedural though, rather than OO even :)

    I have heard the Jini guys talk about Jini as "Network OO"
  20. The interesting things about declarative services using Aspects is that at compile-time there is absolutely no knowledge from the component to the service, the dependency is inverted. EJB offers this for a few specific services. With Aspects you really could offer this for any service period. The shortcomings I can see might include complexity. I think many are wondering if you can accomplish the same goal in some simpler fashion.
  21. Interesting point about the complexity. We got a glimpse of that when we discovered aspects can adversely impact other aspects. I'm curious to see how this scales.
  22. There's a lot of exploration that has to take place before we'll know the right best practices and patterns for good AOP, just like it took for OOP. But I definitely think this has a bright future.

    As far as Native JVM support goes, I think this points at the important question of WHEN aspects can be bound. Right now AspectJ requires all aspects and branch-cuts to be known at compile time, which requires me to have access to your source code to hook into it (say if I wanted to add security to your component). It could be incredibly powerful if aspects could be bound at linkage time, load time, or even runtime, without sacrificing efficiency. That's where the native JVM support may come in to the picture.
  23. Also, aren't the AspectJ guys looking at weaving at the bytecode level, instead of source code?
  24. As I see it, good OOP with wise use of design patterns solves the same problems (programming by interfaces + use of delegation).
    Also I understand some code will be generated for you by the weaver and I tend to be nervous anytime this happens as I don't have much control on it.
    The benefit I see is that using the weaver there's less code to write and maintain.
    The drawback is that code will be generated for you and I'm always a bit nervous when this happens as one has not got much control of it.
  25. Interesting, but for this to succeed it has to be easier to understand AO programs than OO programs. Otherwise it's cheaper to use well-known design patterns.

    IMHO a new language is warranted to a) correct a risky feature of another language or b) to provide support for a new hardware feature. Java is a good example of this economical approach: they kept the C++ syntax but removed memory management and added threads.

    Some features that are clearly needed, and that might warrant a new language are internationalization and evolvability. Internationalization gets really ugly right now, and it's a "cross-cutting concern" if I ever saw one. And we still don't have a nice way of running different transactions in different versions of the system at the same time. Perhaps AOP can help there?

  26. <Interesting, but for this to succeed it has to be easier to understand AO programs than OO programs. Otherwise it's cheaper to use well-known design patterns.
    >>>

    IMO, it *is* easier to understand AO than OO programs, when the aspects capture signifcant crosscutting concerns. Design patterns are not all that easy to understand, and often trade flexibilty for comprehensibility. One thing that Aspects can actually do very well is to encapsulate some design patterns in a single and reusable location. For instance, the docs on www.aspectj.org show how to implement Observer-Observable in a single aspect.

    Also, AOP complements OOP, it doesn not replace it.

    <IMHO a new language is warranted to a) correct a risky feature of another language or b) to provide support for a new hardware feature.
    >>>

    I would disagree with this analysis. These seem like a very limited set of circumstances.


  27. AOP really is a concrete application of what Lisp (CLOS, really) programmers had available for some time with their meta-object protocol...(Gregor Kiczales original work was in this area)... It adds structure and discipline to make what is effectively "language modification" in a palatable way.

    I think AOP really is inheritance's long lost sister. We've had two ways to build upon abstractions with objects: inheritance and composition (aka delegation or decoration). But composition really was tedious compared to inheritance, because we had all of those delegations to perform. AOP simplifies the expression of abstraction in a language.

  28. Internationalization is a great candidate for AOP. Keeping even basic the localization code well-modularized can be a losing proposition in an OO langugage like Java because this concern crosscuts the primary decomposition of your system. It gets a lot worse if you consider the internationalization of concerns beyond those in the surface elements of the user interface (see http://interneg.org/interneg/research/papers/2001/01.html).
  29. Aspect Oriented Programming: The future?[ Go to top ]

    "Internationalization is a great candidate for AOP. "

    I agree but can't seem to see how it can be accomplished. AOP seems to support late-binding flow-control composition. But with I18n, the level of detail is at the ivar. I need to lookup a string and then format it, then use it. Or I may need a different layout for a particular locale. How with AOP?

    Frankly, I see huge possibilities for applying AOP to GUI development. Generally, your basic Main class that extends javax.swing.JFrame is jam-packed with cross-cutting concerns.
  30. Aspect Oriented Programming: The future?[ Go to top ]

    While we're at it, I'd like to add that the bookkeeping for (runtime) monitoring of any sufficiently complex subsystems is a concern that tends to cut across a large number of classes typically.

    While it can be structured using an appropriate set of helper-classes and strict adherence to coding rules, I've found that grouping the monitoring (i.e. the fields introduced [ups, yep I know that old terminology Gregor], the inc/dec at method ends, etc.) into a tangible aspect lets you get rid of all the spread-out monitoring code and have it in a single place.

    It works - try it.

    The other use, I found works well in practice is "caching". I'm not talking about EJB caching here (which is a distributed systems issue), but I mean all those Maps that you sprinkle in your code to store the result of some local computations or some network call. The logic is usually independent of the actual computation/action performed to arrive at a result. Thus you can write aspects that wrap around the computation/action. You can plug/unplug different caching strategies based on e.g. whether you want a hashtable per-object, or a static one shared among all instances, what objects to purge when the cache gets full, etc.

    This one might be worth adding to the AspectJ tutorial.
  31. Here is an example of your caching. The aspect is called memoization and it dramatically reduces the number of recursive calls in the rather naive implementation of Fibonacci. Using aspects this way allows you to experiment with different caching strategies without ever touching the core algorithm.

    public class Fibonacci {

      // naive implementation of fibonacci, resulting in a lot
      // of redundant calculations of the same values.
      public static int fib(int n) {
        if ( n < 2) {
          System.err.println(n + ".");
          return 1;
        } else {
          System.err.print(n + ",");
          return fib(n-1) + fib(n-2);
        }
      }

      public static void main(String[] args) {
          int f = fib(10);
          System.err.println("Fib(10) = " + f);
      }
    }

    And the aspect is here:

    public aspect Memoization { // NOT a typo...

      private HashMap cache = new HashMap();

      private pointcut fibs(int in):
            execution(int Fibonacci.fib(int)) && args(in);

      // calculate only if not already in cache!
      int around(int in): fibs(in) {
        Integer result = (Integer)cache.get(new Integer(in));
        if (result == null) {
          int f = proceed(in); // not found, calculate!
          cache.put(new Integer(in), new Integer(f));
          return f;
        } else return result.intValue(); // found, done!
      }
    }


    Frank
  32. My employer has made the presentation I gave on this
    available on our website, so for those who are interested:

    http://www.trcinc.com/knowledge/presentations.asp

    Frank
  33. Aspect Oriented Programming: The future?[ Go to top ]

    Booch indicated very strong backing for AOP in a recent interview (http://msdn.microsoft.com/msdnmag/issues/02/02/TalkingTo/TalkingTo.asp)


    "I alluded to this notion of multiple views, which leads me to the next great leap I see&#8212;the notion of aspect-oriented programming (AOP), which has been pioneered by Gregor Kiczales of Xerox PARC and others."
  34. Seems that AOP would work very nicely with design by contract.


  35. Yes, that works fine. Beside using AspectJ for logging and profiling our EJB applications (great win), we are starting to use AspectJ for DBC. We could use iContract, but we prefer to limit the use of tools. Our goal is to use DBC declariotions in the javadoc comments and generate AspectJ classes (xDoclet perhaps). Another approach would be annotating UML classes and generating the necessary AspectJ aspects.

    bye
    -stephan
  36. We are also using AspectJ for logging/notification with our EJB applications. AspectJ provides a very clean way to separate these types of concerns from the core business processing. Since the applications we produce are used by multiple customers, we are also considering using aspects to modularize customer-specific business logic.
  37. Aspect Oriented Programming: The future?[ Go to top ]

    Perhaps I haven't investigated 'design-by-contract' enough, but it seems that DBC and unit testing aim to provide many of the same services. What are the primary differences and advantages/disadvantages of each approach? Thanks.
  38. The above article on AOP was really good - well written Ramnivas - thanks. It introduces the topic well.

    I'm a newcommer to AOP and find the paradigm (is paradigm too strong a word for AOP?????) a good move forward. The AOP idea is powerful and will, no doubt (IMHO), reduce the coginitve load on us developers: under AOP, we lowly developers only need to deal with one aspect at a time - instead of dealing with the code that has all aspects fused together - like we do now!. No doubt that will reduce bugs and reduce complexity of the code - a winner in my opinion..... I can imagine that AOP will also affect team dynamics - allowing different team members to work on different aspects of the same object/component/etc.

    AOP also interesting because Persistence in the form of EJB is really just another aspect - an aspect that could be replaced with any other persistence management technology (if you really wanted to) - e.g Scott Ambler's persistence mechanism, etc.. Has anybody placed their persistence/session management into an aspect? How have they found the code design?

    Still, the most important things to me are the basics being new to AOP (and willing to learn from you vetrans).....

    so.....

    How have poeple arranged their source code with Aspects(Aspects in different files, in the same file as the main business logic, etc.)?

    How have people found debugging Aspects?

    How are people arranging their teams under the AOP paradigm?

    Overall, I'm looking to using AOP in the near future.... Oh, I'm looking forward to the replies as well...

    See ya

    Andy

  39. Seems that AOP would work very nicely with design by contract.
    I do believe AOP and DBC fit nicely together. About two years ago I wrote a small library that implements DBC for Java using dynamic proxies (dbcproxy). The problem with dynamic proxies though is that it's not completely transparent in your code, you must wrap your target object with a dynamic proxy. Another thing is that dynamic proxies can only handle interfaces. Anyway, I rewrote my small dbcproxy library (now called dbcaop) to use JBoss-AOP instead of dynamic proxies. By doing that the drawbacks of dynamic proxies disappeared.

    Here is the link to the library if anyone is interested:
    http://www.geocities.com/eliassonaand/project-home.html
  40. AOP already in Java?[ Go to top ]

    Someone here casually mentioned Dynamic Proxies; I feel this is very much AOP at heart! All of the crosscutting system-level concerns the article mentions: handle logging, transaction integrity, authentication, security, and performance, should be implemented at method-level granularity (pre/post method hooks), and Dynamic Proxies, when cleverly coded, can simulate this transparently. For example, I have used DPs to generate RMI stubs (EJBHomes and EJBObjects) that provide transparent logging and failover-in-non-clustered-nodes. Dimitri has done something similar, allowing transparent intercept at every level on and below InititialContext, published here.

    What I like to see eventually is pre-post method hooks built into java's Object class itself:

    public class Object{
        ...
        public void preInvoke(Method method, Object[] params);

        public void postInvoke(Method method, Object[] params, Object return);
    }

    James Gosling wanted this originally in Java 1.0, but was held back and hints of reinstating it in the future (2.0??) With built-in Object hooks, the possibilities are ENDLESS!

    Gene
  41. AOP already in Java?[ Go to top ]

    <quote>
    public class Object{
        ...
        public void preInvoke(Method method, Object[] params);

        public void postInvoke(Method method, Object[] params, Object return);
    }

    </quote>

    I wonder if it would be that useful. From my experience, bugs are usually based on instances of objects, not classes. With the code above, the trace would be displayed for all the instances of the given class, which would probably end up in overly verbose traces.

    You can trace individual instances at creation time by overriding the suspected method:

    MyClass mc = new MyClass() {
      public void bugHere() {
        System.out.println("Entering bugHere");
        super.bugHere();
        System.out.println("Exiting bugHere");
      }
    }

    Can AOP help instrument instances of objects instead of clsses?

    --
    Cedric
  42. AOP already in Java?[ Go to top ]

    Gene, Cedric,

    I have built an AOP-ish framework based on dynamic proxies that indeed allow for per-instance extension of both features (=more interfaces supported by the object) and behaviour (=interceptors). It was very easy to do, and didn't impact the objects that much. What's even nicer, these extensions can be local in space/time, so you can extend an instance for the duration of a method call (for example) and then throw away that extension. Other methods working concurrently with the object will not see your changes to the object. Also, the implementations of the feature extensions can themselves be built using the framework, hence giving it an almost fractal property. Pretty cool.

    From what I can see, AspectJ does not allow this kind of local per-instance runtime extension of objects. Correct me if I'm wrong.

    There was some performance overhead with it, naturally, but it VASTLY simplified the code. Also, I'm doubtful that any other constructions to solve the *same* problem would be much faster.

    /Rickard
  43. AOP already in Java?[ Go to top ]


    Regarding AOP and dynamic proxies.

    Summary: Dynamic proxies (aka interceptors) (as described by Pascal Constanza on aspectj-users, or in the message from Gene Chuang on theserverside) are primitive reflection, and as such they provide crosscutting power. So they have a lot in common with systems like AspectJ. But I believe using an AOP system like AspectJ makes it much easier to develop clean, elegant, reusable crosscutting code. Notably, proxies do not allow systematic specification of where a concern is applied.


    Long argument:

    Hooks like preInvoke and postInvoke are a primitive reflective mechanism. I think this point doesn't need elaboration.

    In the last 15 years we have learned a lot about reflection. I would argue that one of the main things we learned is that in its primitive form, reflection is difficult to use effectively. Note this is NOT an argument about power -- reflection is ultimately more powerful than AspectJ. One key reason is that reflective mechanisms let you use the full programming language in the code that "goes meta". This means it is easy to write programs with meta-dispatching behavior that is difficult to understand. Systems like AspectJ use a declarative language for that dispatch, and hence are easier for tools and people to reason about.

    Compare the following two critical code segments:

      protected boolean isChangeMethod(Object target, Method method) {
         return (target instanceof SimpleModelInterface) &&
         method.getName().startsWith("set");
      }

      pointcut change(SimpleModelInterface subject):
         call(void set*(..)) && target(subject);

    These are the parts of the interceptor and AspectJ implementation of an observer pattern that determine what is a change.

     - Both are about as long, so conciseness isn't a factor (at least in this part of the code).

     - A key difference is that the AspectJ code is declarative. One consequence of this is that the IDE can "understand" the code. It can easily implement the feature of displaying an annotation next to the code for each of the set* methods saying there is advice on it.

     - Another consequence of the code being declarative, is that it is easy to distinguish what is an inherently static test, and what is an inherently dynamic test. In many cases of using AspectJ, there will actually be no runtime evaluation of the pointcuts. It is possible, but not certain the JIT would achieve the same optimization of the isChangedMethod.

    A final difference is that in the interceptor case, you still need to find a way to get your hands on the objects you want to intercept calls to. In patterns like Observer, where an explicit addObserver call is part of what you want to do, that is not a problem. But there are many cases where you don't want to have to "register" the object first -- you want the power to say that all objects of certain types have this new crosscutting behavior. AspectJ makes that easier.


    So I don't argue that dynamic proxies are not at all AOP like: they are (a limited form of) primitive reflection, and reflection is in the roots of AOP. I just believe that newer forms of AOP like AspectJ make it easier to write aspects that have nice properties like being abstract, composable, reusable etc. And the kind of tool support that we can provide for AspectJ far exceeds what is possible with dynamic proxies.


  44. AOP already in Java?[ Go to top ]

    Thanks for the information. I think someone had also mentioned before performance issues and as far as I'm concerned, Aspects can deliver a highly performant solution while reflection can incur overhead.
  45. AOP already in Java?[ Go to top ]

    I wonder if it would be that useful. From my experience, bugs are usually based on instances of objects, not classes


    Ok, let me propose a third hook, Object.postInvokeException(). This would only be called by the VM if an Exception throws out of the method. It's debatable whether postInvoke() should be called as well... perhaps we can have a fourth hook, postInvokeFinalizer(), to do cleanup/finalization of whatever we started in preInvoke, such as performance timing, transaction closing, etc. Hence here's what my proposed Java 2.0 Object looks like:

    public class Object{
        ...
        public void preInvoke(Method method, Object[] params);

        public void postInvoke(Method method, Object[] params, Object return);

        public void postInvokeException(Method method, Object[] params, Throwable thrownException);

        public void postInvokeFinalization(Method method, Object[] params, Throwable thrownException, Object return);
    }

    With these hooks you can implement class-level aspects as well as "exceptional" instance aspects. Mr. Gosling, are you listening? :-)

    Gene
  46. Hi All,
    I am absolutely new to AOP, I have just read the article and some AspectJ documentation. But I can't share your excitement.
    I am not sure I would like to allow an automatic tool to change my code so deeply. I am not sure that injecting massive piece of code in my classes is so appealing. Code generators have pros and cons. What about when a class doesn&#8217;t behave as expected?
    From the documentation of aspectJ:

    aspect PointObserving {

       private Vector Point.observers = new Vector();

       public static void addObserver(Point p, Screen s) {
          p.observers.add(s);
       }

       public static void removeObserver(Point p, Screen s) {
          p.observers.remove(s);
       }

       pointcut changes(Point p): target(p) && call(void Point.set*(int));

       after(Point p): changes(p) {
          Iterator iter = p.observers.iterator();
          while ( iter.hasNext() ) {
             updateObserver(p, (Screen)iter.next());
          }
       }

       static void updateObserver(Point p, Screen s) {
          s.display(p);
       }
    }

    Why should I do something like that? If I need to change the Point class to become observable, I would like that somebody design it in a proper way, not simply inject code with a rule like the one above.

    Maybe I don't see the real power of the paradigm, but it doesn't seem to me a revolution. Where am I wrong?

    Stefano


  47. I agree with your points Stefano. But I, too, am missing something. What does AOP give you that Observer, Mediator, etc patterns don't give you? For AOP to be useful (at least in how it was presented) it would need to be available at a different level. At the binary level perhaps; it would need to be language neutral.


  48. In some ways, you could look at it as language direct support for these patterns - so that you don't have to implement them again and again and just use them.
    Some people termed it a paradigm shift - I see it more as a pattern (or a group of them) becoming so widely used and popular that it makes sense to embedd it directly in a language and make it formal.
    You could (and some people probably will) argue about whether aspects are superset of those patterns or the other way around though :).
  49. Posted by Sartoris Snopes 2002-01-23 11:11:22.0.

    > I agree with your points Stefano. But I, too, am missing something. What does AOP give you that Observer, Mediator, etc patterns don't give you? For AOP to be useful (at least in how it was presented) it would need to be available at a different level. At the binary level perhaps; it would need to be language neutral.

    One way of looking at patterns like Observer is that they give you "conceptual modularity".

    Observer says, roughly that your system has a clear design element, the subject/observer relation, that, unfortunately, is spread out in code. But by calling it "an instance of the Observer pattern" you get some intellectual leverage over the spread out implementation -- you can see it as a single thing even though it isn't in a single place.

    What AOP and AspectJ give you is a way to make the actual implementation modular -- that is, localized and with a clear interface to the rest of the system.

    Using AspectJ, as well as an ObserverPattern library aspect, you can write code like the following:


    public aspect FigureElementDisplay extends ObserverPattern {

      declare parents: FigureElement implements Subject;
      declare parents: Display implements Observer;

      pointcut changes(Subject s):
          call(void FigureElement.moveBy(int, int)) ||
          call(void Point.setX(int)) ||
          call(void Point.setY(int)) ||
          call(void Line.setP1(Point)) ||
          call(void Line.setP2(Point));

      void updateObserver(Subject s, Observer o) {
          ((Display)o).repaint();
      }

    }

    The three parts of the code say:

      - in this instance of the observer pattern, FigureElement plays the role of subject, and Display plays the role of Observer.

      - there are 5 method calls that change the state of the subject

      - the way the display updates is simple (in this case), it just calls repaint on itself.


    If you implemented this without AspectJ, you would have code spread out in:
      
      - 3 methods of Point
      - 3 methods of Line
      - and 1 method of Display

    Not all patterns benefit this much from using AspectJ. At UBC we are now doing a careful study to see which do and don't. But patterns that involve crosscutting should all benefit at least a fair amount.
  50. On the other hand, while not all patterns may benefit
    as much, some patterns become completely obsolote...
    The Visitor pattern is one of those. The entire reason
    for the Visitor pattern is to introduce new behavior
    into existing data structures without directly modifying
    those structures. With AOP, one can simply augment the
    data structures with an aspect, without directly modifying
    them... I don't have the URL handy right now, but there is
    a nice paper on the Visitor pattern in relation to AOP
    titled "Aspect-oriented dependency inversion" by Martin
    E. Nordberg III in which he explains that the Visitor
    pattern breaks all the rules of peroper code dependencies
    and why all those problems dissappear with an AOP
    "Visitor" (which is not really a Visitor)

    Frank
  51. Here's the URL for that paper Frank mentioned:

    http://www.cs.ubc.ca/~kdvolder/Workshops/OOPSLA2001/submissions/12-nordberg.pdf
  52. Hi Stefano,
    the point of AOP is to be able to merge various patterns/features without having to hand-code them every time.
    You are correct in saying that if you want your Point class to be observable you can design it to be so.
    But if you want to add logging, persistence, whatever else you again have to do so yourselv.
    The idea with aspects is that all this can be defined only once somewhere and then seamlessly added to the class when and as needed.
    You could do it (to some extent) in C++ with multiple inheritance. Before dynamic proxies it was quite hard to do in Java, and even dynamic proxies fail to do everything I would like to have :).
    Aspects is just something that formalizes it.
    You could do things that were very close to OO even in some structured-programming languages (i C with method pointers etc.) it just was very hard to code and even harder to read.
    OO clearly defined these things and required explicit support for them.
    In the same way, you can do aspects-like things in OO languages, it's just less formal and well defined. That is, in sense of commonalities - with making something an aspect it's clear what it is and how it's intended to be used and everyone familiar with, say, AspectJ, knows what you meant. If you do it with dynamix proxies, even people who know Java might fail to entirely grasp what it is about, not to say develop something to extend it.

    Oh yes, code generators - unless you code directly in machine codes (below even assembler level), you are alway using some code generator, just of various complexity :) (sorry, couldn't resist).

    I agree with Stu that aspects are long lost inheritance's sister and I have been moaning about adding something like that for years now. In fact I would take some things even further but that's a different story :).
    Regards,
    Vlad

  53.   I am absolutely new to AOP, I have just read the article and some
      AspectJ documentation. But I can't share your excitement.
      I am not sure I would like to allow an automatic tool to change my
      code so deeply. I am not sure that injecting massive piece of code in
      my classes is so appealing. Code generators have pros and cons.

    There's a fundamental point to address here, that often comes up when people first look at AOP and AspectJ. With regard to your message, we would say that AspectJ is not a "code generator", it doesn't "change your code", and it doesn't "inject massive pieces of code".

    Let me try to explain what I mean.

    AspectJ is a simple extension to the Java language, that adds new mechanisms in some ways similar to methods and method call. The AspectJ compiler works in a way similar to the Java compiler -- its job is to implement the AspectJ semantics.

    This is not just a minor distinction of words I'm making. Because AspectJ is designed as a language it has important properties that would not apply if it was designed as something that inserted or copied code.

    For one thing, the access protection works in the proper modular way. (See the private observers field below.) Also, the IDE support understands what's going on. The debugger support (that we are still developing) can understand mappings back to original line numbers etc.

    In terms of the example you have, here are some concrete advantages to doing this with AspectJ, rather than by hand.


    (1) This code is modular, and so it can be removed from the system without having to edit the Point class at all.

    aspect PointObserving {

       private Vector Point.observers = new Vector();

       public static void addObserver(Point p, Screen s) {
          p.observers.add(s);
       }

       public static void removeObserver(Point p, Screen s) {
          p.observers.remove(s);
       }

       /*
        * (2) Shows up here. Note that this will cover all the
        * set methods of Point. You don't have to go to each
        * method and add the call to update by hand. This has
        * several important maintenance advantages. One is that
        * if someone adds a new set method, this will automatically
        * apply. The other is that it provides a clear declarative
        * reading of the (crosscutting) design invariant -- that
        * all set methods are changes.
        */

       pointcut changes(Point p): target(p) && call(void Point.set*(int));

       after(Point p): changes(p) {
          Iterator iter = p.observers.iterator();
          while ( iter.hasNext() ) {
             updateObserver(p, (Screen)iter.next());
          }
       }

       static void updateObserver(Point p, Screen s) {
          s.display(p);
       }
    }

    As a note, in our IDE support, when you go look at the Point class, you will get an automatic reminder of the effect of this aspect. In the emacs version it would look like this. The key thing is the '[PointObserving]', which is an automatically generated hyperlink back to the aspect. With this kind of IDE support you get both the benefits of having PointObserving modularized, and also the nice spread out reminders of where it applies. In more GUI oriented IDEs this would look different, but it would have the same information content.

    class Point {
        private int x = 0;
        private int y = 0;

        ...

        public void setX(int nx) { [PointObserving]
            x = nx;
        }

        ...
    }

    You say:

        Why should I do something like that? If I need to change
        the Point class to become observable, I would like that
        somebody design it in a proper way, not simply inject code
        with a rule like the one above.

    The AOP idea is that this *is* designed in the proper way. Its just that we are doing two things here you can't do with OO alone. One is to modularize the observer pattern part of the relationship between Point and Screen. In this code that all appears in one place. The other is to capture the crosscutting explicitly. In plain Java, this code would be spread out.

    So, if you tried to build this directly into Point and Screen, it would be spread out in the code -- we believe that lack of modularity is a real problem.

    So there is new power here. It is in some ways analogous to when OO was first proposed so long ago. In some sense OO wasn't needed, because they already had callbacks. But in fact adding explicit OO was a powerful addition, because it provided linguistic support for a very powerful program structuring paradigm. That's what we are trying to do with AOP and AspectJ -- add a new program structuring paradigm aimed at modularizing crossscutting concerns.
  54. I totally agree and want to thank the Xerox team for
    developing AspectJ. I was asked many of these questions
    when I introduced AOP and AspectJ to my coworkers in a
    two hour presentation on this topic, and I found the
    following to be an explanation that got the point across,
    (at least to them :-)

    The whole point of AOP is to eliminate cross-cutting
    concerns. If there were no cross cutting concerns, there
    would be no need for AOP. So we should ask ourselves
    why we have these cross-cutting concerns in the first
    place. If you have ever tried to display three dimensional
    data in a two dimensional table, you have probably noticed
    that you get massive repetition, tables in tables, etc.
    The same happens with code: Think of your 'normal' code
    as two dimensional (which is why UML class diagrams work).
    Any OO or other decomposition of your system is 2 dimensional without AOP. A cross cutting concern gets
    scattered all over your code because it is being 'rendered'
    in the wrong dimension! We are lacking a dimension in code
    to cleanly represent them.

    AOP adds this 3rd dimension to your code and ejects the
    cross-cutting concern from the two-dimensional plane into
    this new, third dimension. (And this is why a design level
    notation for AOP doesn't exist yet... It's hard, it's 3D)

    This also ties in neatly with the 'wormhole-effect' which
    allows context passing from point A in your code to a remote
    point B in your code without a direct connection (call) from
    A to B. Traditionally, we'd have to pass one or more extra
    parameters through possibly numerous methods, just to get
    some information to where it has to be. Anyone implementing
    an EJB based system using delegation has done this to deal
    with transactions and security in dependent objects.
    AspectJ allows you to do this directly, because the aspect
    can serve as a wormhole connecting to disjoint point in the
    2D 'object plane' through this aspect dimension where there
    was no connection before we had access to this dimension.
    This is the definition of a wormhole. This IMHO is one of
    the more powerful applications of AOP that has huge
    implications for dealing with functional parts of your
    systems as opposed to systemic (logging, tracing etc) parts.


    Also, I think it is important to distinguish between the
    dynamic nature of AspectJ (pointcuts) and the static nature
    (introductions). These are two completely different
    'kinds of AOP' IMHO. A combination of the two with use of
    abstract pointcuts is esp. powerful and allows us to completely (100%) encapsulate complex protocols and patterns in a single place and apply them to your application specific code with one or a few lines of code.
    Most importantly, this code is declarative,
    simply stating that a class or group of classes should
    have some behavior, not the behavior itself (that lives
    in the abstract aspect).

    I used the above approach to implement transactional java
    objects and was able to completely hide *all* code related
    to tranasactions. Using it simply requires something
    like:

    aspect MyTransactions extends Transactions {

      declare parents: domain.* implements Persistent;

      protected pointcut requiresnew():
            call(* Main.cmNestedAbort(..)) ||
            call(* Main.cmNestedCommit(..));

      protected pointcut requires():
            call(* Main.createCustomer(..)) ||
            call(* Customer.incCredit(..)) ||
            call(* Main.collectionsTest(..)) ||
            call(* Main.manualNested(..)) ||
            call(* Main.containerNested(..)) ||
            call(* Main.clearAddresses(..)) ||
            call(* Main.manualAbort(..)) ||
            call(* Main.updateCustomer(..));
    }

    This is ALL you have to write to make all classes in the
    domain package behave as persistent objects. These classes
    are totally unaware of this fact. The pointcut defs are
    ALL that is needed to specify these methods has having
    transaction boundaries. All the details on how this
    actually works are hidden in the Transactions aspect.
    Note that the domain objects know nothing about persistence
    and transactions *AND* the transaction/persistence code
    knows nothing about the domain objects. It would take
    massive frameworks (like EJB 2.0 CMP :-) to accomplish
    this without AOP. This AspectJ based code is a couple of
    hundred lines of code, that's it...

    In short, to answer the first poster's question:
    I will most definitely use AOP (read AspectJ) on my
    future projects and not just for instrumentation, but for
    actual functional aspects (no pun intended) of the
    production code.

    Just my 2 cents... I'll stop rambling now. If you're
    still with me, thanks!

    Frank Sauer
  55. Oh,Frank.Thanks for your explanation!And "wormhole" is just cool, it is the best description of AOP's power!I belive AOP's logo(if some guy likes to design one) should has one on it.
    But don't you think "3D" is too few?I think multi-dimensional is better.
    Afterall,our university is 11D.
  56. Sorry.I mean our universe is 11D.
  57. Correct, IBM's folks (HyperJ) use the term
    multidimensional separation of concerns. I think they
    consider each aspect a separate dimension. I just
    lumped all aspects together in a third.
    Each cross-cutting concern (scattered in 2D) collapse
    into a single point in this third dimemension.
    I find this a workable model without it becoming
    totally abstract. What does 11D look like? :-)
  58. According to a strange but serious theory of current theoretical physics,we are now living in an mutil-dimension space,maybe 11D.
    So look at your computer,and your will know 11D looks like what.

    http://superstringtheory.com/
  59. Just a quick point I'd like to clear up: Not every aspect results in a wormhole. 'Wormhole' is just a name for one particular AspectJ idiom, namely 'cflowbelow(pc1) && pc2' where pc1 and pc2 are pointcuts. There are other idioms as well, like non-reentrant or 'pc && !cflowbelow(pc)' to capture only first time entries into a particular pointcut.

    Frank
  60. I feel a little disappointment.Wormhole is so cool.
  61. Aspect Oriented Programming: The future?[ Go to top ]

    Thanks Frank, excellent description. I've been a bit confused about where AOP fits in (and still am) but it's starting to make sense.
  62. The second part of the article is now published at JavaWorld:

    http://www.javaworld.com/javaworld/jw-03-2002/jw-0301-aspect2.html?