Tuesday 31 January 2012

AOP , Dojo and the Eventlistener

One of the most revoloutionary concepts to emerge after OOP ( ofcourse,the same OOP invented centuries back just after the invention of the fire and wheel ) is aspect oriented programming or AOP. While AOP has still not been widely adopted on a level that such a simple and amazing concept is expected to , nevertheless it has inspired enough people to spawn various language improvements, implementations and achitectures.
For those unfamiliar with AOP , a simple way to put it is -> injecting code at specific conditions called join points
Example of join points are :
-Function execution ( entry , exit and processing )
-Field change  -> i.e getters and setters
-Exception Conditions

The injection of code basically ensures that only business logic needs to be written in the function and other aspects such as :
-Logging -> the most irritating aspect of programming especially with property files
-Exception Handling
-Tracing

Ok , AOP is awesome - how do you use it ?
Well , while an enterprise implementation of AOP might need a new language ( think aspectj ), a framework (spring AOP ) or maybe an amazing architecture.It is actually quite simple to implement it to a limited level in javascript with dojo .

A simple AOP "hello world" would look like this (for those who understand java better than english)  :

Main.java  :
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World ");
    }
}


Aspect (pseudocode) : logging.aspect ( or logging.aj if you are using aspectj)

public aspect log {
    //The pointcut or jointpoint - this is the place to specific code conditions
    pointcut logEntry() : execution(* *.*(..));
  
    //The function to be executed before the condition occurs
    before() : logEntry() {      
        System.out.println("Entering :"+thisJoinPointStaticPart.getSignature().getName());  
    }
  
    //The function to be executed after the condition occurs
    after() : logEntry() {      
        System.out.println("Exiting :"+thisJoinPointStaticPart.getSignature().getName());  
    }
}


Output :

Entering main
Hello world

Explanation for dummies :
The pointcut in its weird syntax (yeah its aspectj, i accept it ok.. ) is the condition where the code should be injected.
The "thisJoinPointStaticPart" gives us information about the joint point so that we can use it in the function .
It is similar to regular expression to specify a condition (ok not very similar ,regexp fans) where the code can be injected.In this way we can seperate code to be
executed before and after the business logic though it is just "hello world" here.In this way logging is seperated from our business code. In the same way we can seperate exception handling , validation,resource allocation and deallocation e.t.c from our code leading to easy,maintanable and most importantly readable code (ok atleast in theory - we guys can create disorder even with a straight line ).

Now in the real world shifting to AOP would be a pain, the alternatives are
- learn a new language
- learn a new framework
- design an awesome architecture

But in the gravity defying world of javascript it can be quite easy - especially with dojo -that baby dinosaur of a JS library that IBM loves
Dojo has had a package for AOP  from version 1.1 ( wow , even though AOP is quite old) the "dojox.lang.aspect" package

Example code :

dojo.require("dojox.lang.aspect");
var aop = dojox.lang.aspect;


Now that we have the aop object , how do we use it ?
Given that we have a JS class (now don't ask me if JS has classes-they have something in their own gravity defying way  ):

myclass=function(n){
    this.name=n;  
    this.setName=function(n){
        this.name=n;
    }  
    this.talk=function(){      
        console.log(this.name);
    }
}

Now the aspect can be applied to in the following way :

kk=new myclass();
aop.advise(kk, [/.*/], {
    before: function(){
        var instance = aop.getContext().joinPoint;
        console.log("Entered "+instance.targetName);
    }
});

Yes , the same weird syntax that you can find no documentation about .Well but the code seems quite simple
"kk" is an object and a regular expression(the 2nd argument) is applied on it so whenever its functions are called the code is executed before it .

Now before you want a tutorial or actual documentation ,it'd be better to explain why you actually might use it - especially in javascript !
Javascript is possibly the worst language to write structured code - since it is gravity defying in every way (yes it seems to want to use every new language
concept that is being thought of ) and that is exactly the reason why it is even more harder to actually find the place where we might want to add some code. JS if well written ( i can't say that with a straight face ) can be extremely unreadable and AOP provides a good way to add code and seperate it from the original code without actually reading the code -just plain playing with it in the firebug console would do .
But the main reason are Eventlisteners :
- While JS took visual programming to a new,easier and standard level it created something called eventlisteners. Now while they are awesome but
the only issue with them is that the function could have been attached anywhere in millions of lines of obfuscated JS code or in the hundreds of JS
files included onto one JSP file ( think portal and the pagebuilder JS monster ["undocumented monster"] ) .
A simple example:
Given a element as :

<div id="cl" style="display: block;width: 100px;height: 100px;background: black;"></div>

<script>
dojo.addOnLoad(function(){  
    k=new myclass("Something");
    dojo.query("#cl").onclick(function(){
        k.talk();  
    });
});
</script>
<script>
//The same class we used earlier
myclass=function(n){
    this.name=n;  
    this.setName=function(n){
        this.name=n;
    }  
    this.talk=function(){      
        console.log(this.name);
    }
}
</script>



Now if we want to find out what function was called through the eventlistener , unless we get to the source there is no easy way to find out using firebug(yes the greatest JS dev. tool).A simple printing of the 'onclick' function would have sufficed in simpler times when there were no event listeners.But adding a simple aspect to all the classes in which your custom functions are encapsulated would make life so much more easier in tracing the function call.
Example :
//yeah the same example
aop.advise(k, [/.*/], {
    before: function(){
         var instance = aop.getContext().joinPoint;
        console.log("Entered "+instance.targetName);
    }
});


Now when we click the div area we get :

Entered talk
Something

That makes life so much more easier (especially if you are in a maintenance project like me :) )
-> Add a little more info to your aspect and it becomes the perfect logger without you writing a million lines of code in every JS function.
Now if i could just think of a better usecase - something that is not about logging ,just joking :
-> Animation Triggers - imagine just setting the value of a DOM element and it animates itself
-> Tracing timers , yes we do need to keep track of those functions which can kill your browser
e.t.c ,(yes , i just ran out of ideas)

A complete tutorial on the dojox.aspect can be found here :
http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/
    Author : Eugene - Thank you eugene , you are god !!

Please do check the wiki page on "Aspect oriented programming" and AspectJ language if you like the concept or have finally decided to give it a look