Aspect pattern

Discussions

J2EE patterns: Aspect pattern

  1. Aspect pattern (8 messages)

    The problem:
    There's an cross-cut concern throughout the entire application. One important attribute of the concern is while the concern is wide-spread, an occurrence of the concern (segment of code handling the concern) is particularly localized, which means one occurrence of the concern in particular area of code is somewhat independant with another occurrence. The main challenge remains to keep the concern out from the class and api design or otherwise it will overwhelm the entire api design (e.g. having to pass concern specific information throughout the application).

    The Aspect pattern
    An AspectSingleton is a Singleton that contains a set of related functions that is used throughout the entire application. The AspectSingleton will need be initialized by the AspectInitializer in the application initialization to appropriate context before the aspect become functional.

    Example:
    There are a lot of example of implementations of aspect pattern in java world. Here are just some of them:

    Logging aspect - log4j
    log4j use the Logger class to to achieve the logging aspect. The logger also act as Aspect singleton to allow getting the Logger instances specific to a java class:

    Logger logger = Logger.getLogger(Myclass.class);
    logger.debug("...something...");

    There are different Configurator singletons that act as the AspectInitializer to initialze the configuration of the log4j logger and it is up the the application to use them to initialize the logging context.

    Security aspect - JAAS
    The JAAS API is actually implemented using the aspect pattern. The underlying authentication and authorization is actually done by the AccessController.doAction method. The AccessController is the AspectSingleton and the JVM acts as the AspectInitializer that set up the AccessControlContext use by the AccessController to use for authenticate and authorize. The LoginContext and Subject.doAs() just act as a wrapper to the AccessController in the JAAS api

    Other examples: JNDI?

    Benefits
    Using aspect, the application is freed from the burden to explicitly handling the aspect in the api design. The concern become a set of design/implementat issues that can be worked on independantly. Also, the coding explicit is more explicity than bytecode-instrumentation such as AOP.

    Caveats
    It is important to identified when to use the Aspect pattern since the Singleton can cause a lot other design problem when use improperly

    Relations to other framework
    AOP - while AOP most refers to code instrumentation, the Aspect Design made the coding more explicit
    - it does not work at any grain level of code
    - predesign the aspect before coding
    Spring - One of the feature of Spring is to support IoC and eliminate the Singletons in the system. The thing is that simple IoC can still be achieved by appropriate framework design (best approach), or otherwise using the Aspect pattern here as last resort. Spring replace singletons in the system with one universal singleton that does it all, I'm not sure how it will improve the design of the application. E.g. imagine the log4j, jndi, jaas all implemented using Spring.

    Threaded Messages (8)

  2. Abstract Factory?[ Go to top ]

    1) What you are describing here --- isn't that a plain Abstract Factory?

    In your logging example:

     Logger logger = Logger.getLogger(Myclass.class);

    The Logger class is the factory (in particular the getLogger static method).

    The "special" thing, that the Logger class does, is to create an object from some kind of configuration that implements a particular interface (or in this case, extends the Logger class itself).

    And what do the GoF say about Abstract Factory?

    Applicability:
    Use the Abstract Factory pattern when
    * ...
    * a system should be configured with one of multiple families of products.
    * ...

    Sounds to me like the same thing...

    2) I don't quite understand the line
    AOP - predesign the aspect before coding

    3) "imagine the log4j, jndi, jaas all implemented using Spring."
    Why not?

    public Class MyClass {
      private Logger logger;
      public Logger getLogger() {
        return logger;
      }
      public void setLogger(Logger newLogger) {
        this.logger=newLogger;
      }
      public void foo() {
        getLogger().info("Wow, where did the logger come from!");
      }
    }

    No need to ask Logger.getLogger to create your Logger instance - you just have it!
  3. Re: Abstract Factory?[ Go to top ]

    1) What you are describing here --- isn't that a plain Abstract Factory?In your logging example: Logger logger = Logger.getLogger(Myclass.class);The Logger class is the factory (in particular the getLogger static method).The "special" thing, that the Logger class does, is to create an object from some kind of configuration that implements a particular interface (or in this case, extends the Logger class itself).And what do the GoF say about Abstract Factory?Applicability:Use the Abstract Factory pattern when* ...* a system should be configured with one of multiple families of products.* ...Sounds to me like the same thing...
    Yes it is indeed the abstract factory pattern. But the point is that it is a good pattern that handle aspect in a good way as evident in log4j, java security and more. It allows expressing aspect explicit inside the code. I'm sure if it is the BEST way but certainly a good way to do aspect, aside of AOP which make the coding less tractable. Also, it make aspect possible at any grain-level, and make interaction between aspect possible (since it just plain coding).
    2) I don't quite understand the lineAOP - predesign the aspect before coding
    I don't have too much experience in AOP so pardon me if this is wrong. Assume supposed you want to implement crosscut concerns as AOP. Do you need to consider whether it is achievable through AOP, or just totally ignore about the concern until later on? If the former is true, the statement above is true. If later is true, the statement I had is not true but it makes me more worry because this postpones the risk to later in the project.
    Using aspect design pattern, an aspect is designed to be a self-contained, complete framework. You can rest assure that you can always weave the code into the application as it will work.
    3) "imagine the log4j, jndi, jaas all implemented using Spring."Why not?public Class MyClass { private Logger logger; public Logger getLogger() { return logger; } public void setLogger(Logger newLogger) { this.logger=newLogger; } public void foo() { getLogger().info("Wow, where did the logger come from!"); }}No need to ask Logger.getLogger to create your Logger instance - you just have it!
    What I meant is this: consider log4j pattern
    ---
    InputStream is = new FileInputStream("beans.xml");
    XmlBeanFactory factory = new XmlBeanFactory(is);
    factory.getBeans("logger", log4j.class); //now spring a logger
    factory.getBeans("securitymanager", SecurityManager.class); //now spring a security manager, what's next
    ----
    It just that replacing multiple singletons with one singleton, you have a multi-role singleton. I'm not sure whether it is really an improvement. It probably (too) convenient, but I'm just not sure whether there's any impact on design on overall application.
    As for your example, imagine that there's 5 aspects. Then you will have 10 setter/getter, while your class might only have 2 methods that actually "do something", will you be happy :>?

    Again, just my thoughts, any comment is welcome.
  4. Aspect pattern[ Go to top ]

    huh ?
  5. Aspect pattern[ Go to top ]

    Tiong,

    I fail to see how your pattern has anything to do with aspect orientation.

    Aspect orientation is about *applying* orthogonal features to a piece of software. It has nothing to do with self-containment, hiding object creation in factories and so forth.

    The problem an "Aspect pattern" must address is "how do I apply this aspect (i.e. logging, security, modus, whatever) to an entity (construct, method, class, component, program, system, enterprise) that needs that aspect without the entity knowing about it?"

    This usually mean using a weaver, interception/dynamic proxies or on-the-fly code generation. All this approaches adds to the development and production complexity... what we need is first-class constructs in the language to support aspects. One way to achive that would be to support reactive clauses, which is pretty much an "if" statement that get executed when an expression gets true. With that, you can express such things as "when any method is called _AND_ the logging flag is set, use this piece of code to perform logging".

    Thanks.
  6. Aspect pattern[ Go to top ]

    I fail to see how your pattern has anything to do with aspect orientation.Aspect orientation is about *applying* orthogonal features to a piece of software. It has nothing to do with self-containment, hiding object creation in factories and so forth.
    This pattern is also about applying orthogonal concern to a piece of software, without intruding the API and class design of the actual piece of software. It only affect the implementation. The focus is not on the hiding of object creation, but the ability to express a concern, anywhere in a piece of software. You can think of this as an alternative to AOP for implementing cross-cut concern. In fact IMHO it has been a traditional of doing cross-cut concern like in log4j and java security (either it has been informally or many just don't realize that).

    AOP seems to be pretty hot now but I've some concerns with it. For example:

    int fact = 1;
    for (int i=10; i>1; i--){
        fact *= i;
        //I really want to log it
        _logger.log("fact " + i + " = " + fact);
    }

    Two observations can be made from the example above:
    1. The logging is done in the grain-level that cannot be achieve by AOP AFAIK (I don't know AOP deeply let me know if I'm wrong)
    2. The message logged is essentially relevant to that specific segment of code. It seems absurd to me if I have to separate the logging code
    to somewhere else.

    Another concern is regarding interdependence between aspects. For example:

    ...in the application...
    if (SecurityManager.getAccessLevel("Admin")==-1){
        _logger.warn("Intruder here!");
        //do something about
    }

    Here, the security aspect requires the log aspect . Should we have implemented this using AOP, we need to have logging aspect enabled for the security aspect? We will have aspect of aspect. So the AOP need to support dynamic weaving of dynamic weaved code? What if the logging aspect somehow requires security aspect?

    The bottom line is using Aspect Pattern (the traditional way), the weaving is done in place inside the application and it allows maximum control on what you want to do (like the code examples above).

    While the issue AOP try to resolve is code tangling and code scattering (in reference to http://www.javaworld.com/javaworld/jw-01-2002/jw-0118-aspect.html), my stand is that if the tangling and scattering are necessary, let it be.
    The problem an "Aspect pattern" must address is "how do I apply this aspect (i.e. logging, security, modus, whatever) to an entity (construct, method, class, component, program, system, enterprise) that needs that aspect without the entity knowing about it?"
    AOP is a mean to solve some problem associated with implementing cross-cut concerns (see reference link above). Aspect pattern here, advocates a different approach of implementing the cross-cut concerns. So it should not be confused that Aspect pattern here has anything to do with AOP and all it's related concepts.

    Also, it is dangerous to think of AOP as the end while it is just a mean. In the definition given above, "without the entity knowing about it" signifies the thinking that AOP as the way the application should be. AOP is an interesting concepts - but it's too early to think that it is the way the software system should be. It tries to solve certain problems (as mentioned above), but whether it solves the problem the best is yet to be proved.

    Just my thought. Any comments is welcome.
  7. Aspect pattern[ Go to top ]

    So it should not be confused that Aspect pattern here has anything to do with AOP and all it's related concepts.
    Which is why this pattern is perhaps the most confusing one I've ever seen. You state in the first sentence that the pattern is about applying "orthogonal concerns"... Well, that implies that your pattern indeed has something to do with AOP.

    Yet, there is nothing AOP about it. It is just a singleton with "localized code." That's not a pattern, just a singleton with self-containedness as a goal.

    You also fail to mention that singletons have problems:

    1) They represent trouble in the EJB environment, especially containers that don't handle static's well (in particular a bad idea in clustered environments)

    2) Singletons are hard, if not impossible, to extend in any reasonable way.
    Also, it is dangerous to think of AOP as the end while it is just a mean. In the definition given above, "without the entity knowing about it" signifies the thinking that AOP as the way the application should be
    "without the entity knowing about it" is a feature of AOP and I certainly didn't claim "AOP as the way the application should be".

    I don't claim AOP is utopia. It is useful in certain situations.
    (I don't know AOP deeply let me know if I'm wrong)
    You are wrong.
  8. Aspect pattern[ Go to top ]

    Which is why this pattern is perhaps the most confusing one I've ever seen. You state in the
    first sentence that the pattern is about applying "orthogonal concerns"...
    Hm... so "orthogonal concerns" implies AOP. System always have orthogonal concerns (logging, security, persistence). System always have AOP?!

    The thing is that AOP is invented as a mean to deal with orthogonal concern. What is proposed here is just to take a step back, look at an (traditional) approach of doing it, and ask whether AOP can do the same or better (e.g. on the example I gave in previous post)?
    It is just a singleton with "localized code." That's not a pattern, just a singleton with self-containedness as a goal.You also fail to mention that singletons have problems:1) They represent trouble in the EJB environment, especially containers that don't handle static's well
    (in particular a bad idea in clustered environments)2) Singletons are hard, if not impossible, to extend in any reasonable way.
    Perhaps I didn't explain it well enough. The AspectSingleton only act as the accessor to an aspect. There should be a complete set of extensible architecture that allows you to extend the aspect into the way you want it. For example, log4j and java security both provide enough extensiblity on the entire logging and security backend. So this pattern is essentially advocating the design of entire aspect with AspectSingleton as accessor to the aspect.

    The reason AspectSingleton is necessary is because it allows localized expression of a concern, that way the aspect does not creep in API/class design. For example, it is considered to be a bad API if you have to pass a logger in all the constructors of you java classes. Similarly, it will be less than perfect if all your classes have to have setLogger and getLogger. AOP allows clean API design of system because of dynamic code weaver at runtime. This approach allows clean API design of system because of AspectSingleton.
    I don't claim AOP is utopia. It is useful in certain situations.
    No question to that. This post just try to provoke some thoughts that could even make it better. Some fundamental questions:
    - can the whole be achieved by the sum of it parts?
    - if yes, then can the whole be achieved easier by the sum of it parts?
  9. One important feature about an aspect is the fact, that the entity which is adviced by an aspect isn't aware of that aspect. It's even one goal of AOP to modularize a general concern that would be otherwise spread around the whole source (like what you have with Logging using a Logging-API directly: You can see the logging-code scattering all over your classes). So your class can concentrate to it's main responsibility without be treatened to think about such aspects like logging, security, transactions ...
    This is in contrast to the proclaimed 'AspectPattern', where you'll have your 'Aspect' still referenced directly by your classes far from applying your aspect by a pointcut that just 'hooks' in the advised classes, methods, constructors, ...where the adviced class hasn't any knowledge that there is an aspect. You still tangle your actual code with logging-code ...
    If you look for example to the spring implementation of AOP, you can see this idea by applying aspects using the proxy-pattern (i would rather see this as a decorator), where you have an Interceptor (the advice) which proxy the adviced class (where the adviced class has'nt any knowledge of this fact - unless you use annotation-based aspects) using a pointcut.
    Coming to an end - maybe the whole discussion is about the name of the pattern. Using the concept 'aspect' could lead to some Misunderstanding of the application of the pattern.