51

Can anyone post an example of Aspect-oriented programming (AOP) that is not logging?

I've looked at several resources but all the examples are trivial logging. What is it useful for?

Dave Hillier
  • 18,105
  • 9
  • 43
  • 87

14 Answers14

35

One of the examples which was loaned straight from this Aspect Oriented Programming: Radical Research in Modularity, Youtube video was painting to a display. In the example you have a drawing program, which consists of points, shapes, etc and when changes to those objects occur you need to tell the display to update itself. Without handling it in an aspect you end up repeating yourself quite a bit.

AOP, as I've understood it, was created for not repeating yourself for cross cutting concerns which might not have anything to do with business logic. With aspects you can modularize these concerns to aspects. One of the examples was logging but there are bunch of different things you might end up repeating. It has been evolving since and it's not any more about aspect-oriented programming but there's also aspect-oriented modelling.

More information about aspect oriented programming can be found from these sources:

GalacticJello
  • 11,235
  • 2
  • 25
  • 35
Bleadof
  • 1,157
  • 1
  • 9
  • 19
  • AOP is error-prone because there is no localization of changes. It's basically annotations without the annotation declaration (aka invisible annotations). Also see https://pp.info.uni-karlsruhe.de/uploads/publikationen/constantinides04eiwas.pdf – Pacerier Jun 29 '14 at 18:58
  • 4
    @Pacerier: Your statement is false. I have been using AOP for years in order to *avoid* errors and simplify refactoring and debugging. All the cross-cutting code which in OOP is tangled with and scattered across the whole code base is neatly modularised and thus easy to localise in AOP. Core code is easiert to read and maintain. Statements like yours are mostly heard from people who have not grasped the concept of AOP and not used it extensively (beyond giving is a quick try, which just is not enough). – kriegaex Jul 20 '14 at 15:26
  • @kriegaex, When Exactly the concept of AOP has came. – smali Oct 18 '14 at 07:07
  • 1
    @ali786: According to [Wikipedia](http://en.m.wikipedia.org/wiki/Aspect-oriented_programming#History) AspectJ was the first AOP language in 2001. From my experience I can say that it is quite mature and absolutely production-ready today. – kriegaex Oct 18 '14 at 08:58
11

Security

  • Inject code that checks permissions and blocks access

Friendlier error msgs for asp.net webcontrols/webparts

Performance

  • Inject code that sets perf counters to get an overview of where your app is slow
Community
  • 1
  • 1
AndreasKnudsen
  • 3,453
  • 5
  • 28
  • 33
6

Validation:

[NotNull]
public string Property1 { get; set; }

[Length(Min = 10, Max = 20)]
public string Property2 { get; set; }

[Regex(Expression = @"[abc]{2}")]
public string Property3 { get; set; }
Paco
  • 8,335
  • 3
  • 30
  • 41
  • 1
    Where is de Aspect? But you could use some advice to read this "annotations" that come from a joinpoint provided by a pointcute like: * * save(..) Thus you can use a before advice to validate and proceed if so or throwing some fail conditions about the invalid state. – paulosuzart Nov 28 '08 at 12:37
  • It depends on where the validation is used and what kind of UI framework is used. I don't use the aspects on entities that needs to be validated, but more for "defensive coding". I do not use the validation of entities on a save method in a repository, but I validate somewhere in the UI. – Paco Nov 28 '08 at 19:50
  • @Paco, This is not really AOP; it's more of annotated programming than AOP. In AOP, we are not allowed to specify *anything* at the calling site at all. Even the existence of `[NotNull]` is not allowed in AOP. – Pacerier Jun 29 '14 at 17:56
6

Undo - I am calling a third-party assembly that supports undo operations. It requires callers to create an undo context, call some methods in the assembly, adn then destroy the undo context. Contexts can be nested. Also, if a context is created but left in an undesirable state that requires an app restart.

Normally to use undo I would write something like this

    void foo()
    {
        int id = lib.create_undo_context();
        try
        {
            lib.performsomeaction();
            lib.performsomeaction();
            lib.performsomeaction();

        }
        finally
        {
            lib.destroy_undo_context(id);
        }
    }

with PostSharp I define an attribute called [Undo] that creates the undo context when the method starts and destroys it when the method exits (even if an exception is thrown) - so the code looks like this

    [Undo]
    void foo()
    {
        lib.performsomeaction();
        lib.performsomeaction();
        lib.performsomeaction();
    }

It's a little more complicated to implement this than I am showing because I have ensure that all undo contexts are cleaned up even in cases where there are nested Undo contexts - but you get the idea.

namenlos
  • 5,111
  • 10
  • 38
  • 38
5

Dependency Injection

Strictly speaking, dependency injection is nothing more than a crosscutting concern. A lot of dependency injection frameworks use a attribute-based programming style like this:

public class Car:IDisposable
{
    [Inject]
    public IGearBox Gearbox { get; set; }
   ...
}

The [Inject] attribute could also designed as an aspect without any dependency to an external framework.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
wolle23
  • 11
  • 1
  • 1
5

Another classic example (like logging) is caching. But other examples are more interesting.

orip
  • 73,323
  • 21
  • 116
  • 148
4

Design Pattern Implementation in Java and AspectJ (Hannemann and Kiczales): http://www.cs.ubc.ca/labs/spl/papers/2002/oopsla02-patterns.pdf

The paper shows how some of the GoF design patterns can implemented in a better way in Java using AspectJ

Eyvind
  • 5,221
  • 5
  • 40
  • 59
3

Security - checking that users have appropriate permissions prior to executing certain methods.

Dan Vinton
  • 26,401
  • 9
  • 37
  • 79
3

You cannot have multiple inheritance in Java. However by using AOP you can have "limited" multiple inheritance. Try to google this to see some examples.

I also agree with Eyvid. Hannemann and Kiczales paper is great for learning the basics on design patterns and getting some great AOP examples.

Chrys
  • 636
  • 1
  • 7
  • 18
2

Transaction management.

To my mind, you do not want objects that may be part of a transaction to be aware that they are in a transaction. Using AOP, you can compose objects into transactions as required without the objects in the transaction needing to be aware of either the fact that they are in a transaction or even of the existence of the AOP framework.

Alfamale
  • 1,069
  • 1
  • 9
  • 13
2

Examples of AOP:

  • A parser and evaluator for arithmetic expressions. This could have been programmed using the visitor pattern, but I believe that aspects are a better alternative.
  • A simple text editor, in which some management tasks (e.g., maintaining the "file has changed" flag, and the window caption) are treated as separate aspects.
  • A data structure for character strings, in which strings are represented as trees so that concatenation and substring selection can be implemented without copying. To maintain efficiency, the trees sometimes need to be rebalanced; the balancing code is treated as an aspect.

Let's imagine you want to log a message inside methods of your domain model:

Example: Logging without AOP:

namespace Examples\Forum\Domain\Model;

class Forum {

    /**
     * @Flow\Inject
     * @var \Examples\Forum\Logger\ApplicationLoggerInterface
     */
    protected $applicationLogger;

    /**
     * Delete a forum post and log operation
     *
     * @param \Examples\Forum\Domain\Model\Post $post
     * @return void
     */
    public function deletePost(Post $post) {
            $this->applicationLogger->log('Removing post ' . $post->getTitle(), LOG_INFO);
            $this->posts->remove($post);
    }

}

If you have to do this in a lot of places, the logging would become a part of you domain model logic. You would have to inject all the logging dependencies in your models. Since logging is nothing that a domain model should care about, this is an example of a non-functional requirement and a so-called cross-cutting concern.

With AOP, the code inside your model would know nothing about logging. It will just concentrate on the business logic.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
2

Public invariant checking. Since PostSharp 1.5 will come with aspect inheritance, even through interfaces, it will give a lot of new opportunities.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
2

My photo album uses aspectj for three things:

  1. Implementing the observer "pattern" as a reusable piece of code.
  2. Destroying a session for a specific type of call.
  3. Setting dirty flags on DTOs when mutation occurs.

The first, in particular was pretty much straight out of a google tech talk on AOP. It's about modularity in a different way than most people consider. Definitely recommend watching that if you're interested in how to use it for good.

Dustin
  • 89,080
  • 21
  • 111
  • 133
2

I have used aspect-oriented programming to implement a keyword search engine. It was more like an experiment, but it shows how AOP can be used for purposes other than logging and tracing.

Basically:
(i) The user of the engine marks his/her classes as KeywordSearchable,
(ii) The engine starts tracking the creation & destruction of these KeywordSearchable instances,
(iii) The engine extracts the keywords from these KeywordSearchable objects,
(iv) Given the objects and the keywords, the algorithm takes care of the search.

More details on this can be found at http://montrealistic.blogspot.com/2011/08/aspect-oriented-implementation-of.html.

Guven
  • 2,280
  • 2
  • 20
  • 34