AOP use cases

Daniel Dittmar daniel.dittmar at sap.com
Mon Apr 19 11:21:13 EDT 2004


John Roth wrote:
> "Daniel Dittmar" <daniel at dittmar.net> wrote in message
>> AOP grew out of the observation that an evergrowing percentage of the
>> code of the average method is taken over by parts that are not
>> related to the main purpose of the method, but by logging,
>> sychronization, transaction handling and other stuff.
>
> Bad design is bad design. Having methods with more
> than one responsibility is poor cohesion and high coupling.
> Spending a bit of time thinking about how to encapsulate
> this type of crud will pay big dividends. Unfortunately, it
> won't get academic publication credits.

So if you want a feature (= public method) that supports logging +
synchronization + transaction handling + 'the main feature', you'll write
four methods, each one doing it's own and then calling the next layer. This
is certainly doable, but if you do this to several methods in several
classes, you'll be probably asking yourself if there isn't a better way. AOP
tries to be such a way.

> Duplicated code is duplicated code, and should be ruthlessly
> eliminated wherever found. It doesn't matter whether it's
> generated by some tool or inserted by the developer.

It depends on your programming language if every kind of duplication can be
factored out. Assume that you want a variant of a class where several
methods are synchronized. The code for the methods in the new class will
always look like

lock.acquire ()
call_original_method (args)
lock.release ()

I do not see how the duplication in the structure can be factored out in
languages like Java or C++. In Python, I could do the following

class SynchronizedCall:
    def __init__ (self, lock, method):
        self.lock = lock
        self.method = method

    def __call__ (self, *args, **keywargs):
        self.lock.acquire ()
        try:
            self.method (*args, *keywargs)
        finally:
            self.lock.release ()

obj.append = SynchronizedCall (obj.lock, obj.append)
# the following calls to obj.append () will be synchronized

>> And the 'we do this through refactoring' argument ends where you use
>> external libraries unless you want to fork them.
>
> Now you're contradicting yourself. First you say that it's not
> about patching to get around stupid libraries, now you say it
> is about patching to get around stupid libraries.

It's not *only* about patching existing libraries, it's a different way to
structure the code. In addition, it has the potential advantage that you can
adapt existing libraries without having to change them.

Daniel






More information about the Python-list mailing list