{"id":767,"date":"2009-03-31T22:50:03","date_gmt":"2009-04-01T03:50:03","guid":{"rendered":"http:\/\/unitstep.net\/?p=767"},"modified":"2009-03-31T22:52:34","modified_gmt":"2009-04-01T03:52:34","slug":"aspect-oriented-programming","status":"publish","type":"post","link":"https:\/\/unitstep.net\/blog\/2009\/03\/31\/aspect-oriented-programming\/","title":{"rendered":"Aspect-Oriented Programming"},"content":{"rendered":"
I’ve started looking at Aspect-Oriented Programming (AOP)<\/a> recently, because of its potential for improving code readability and maintainability. This is mainly provided by the “separations of concerns” goal that AOP aims to achieve. To get started, I decided to jump in using the jQuery AOP plugin<\/a>. Why jQuery\/JavaScript instead of something more mature like AspectJ<\/a>? Well, for one thing, I have spent quite a bit of personal time developing with JavaScript<\/a> and it seemed like a logical place to get a good footing before diving deeper with something like AspectJ.<\/p>\n <\/p>\n The main aims of AOP are to improve program modularity by increasing the “separation of concerns”. What exactly does that mean? To be certain, plain old Object-Oriented Programming (OOP) already drastically increases program modularity; but there is still room for improvement. In particular, AOP seeks to address the issue of crosscutting concerns<\/strong>, that is, functionality which “cuts across” or overlaps multiple areas of a system.<\/p>\n For example, most web applications will have authentication<\/em> and\/or authorization<\/em> as cross-cutting concerns. Some pseudo-code for showing a user’s personal “Todo” list is shown below:<\/p>\n The act of checking if the user is authenticated has become entangled with the core business logic of showing the items of the “Todo” list. Indeed, this can become cumbersome as the business logic functionality expands; for example, we might have to write such “boilerplate” code to check for authentication for each page that requires it.<\/p>\n Of course, this is just a contrived example. This particular authentication problem has already been nicely solved in many languages such as Java (J2EE) and PHP<\/acronym>. In either of these languages, for instance, you’ll find multiple frameworks that take the grunt work out of a common problem like this, but it highlights how cross-cutting concerns can interfere with and decrease the modularity of a system, making it harder to maintain.<\/p>\n Separation of concerns aims to refactor this code to reduce the overlap in functionality, so that core business logic can be separated from the cross-cutting concerns, which then become known as aspects<\/strong>. One area that AOP suffers from is the confusing terminology. Thankfully, the folks behind the great Spring Framework have written an excellent guide to the terms and AOP itself<\/a>. I suggest you take at least a quick look at it.<\/p>\n AOP achieves its goals by defining join points<\/strong> where certain advice<\/strong> can be executed before or after the code at the join point. A join point is simply a certain point in the program code and is typically the point where a method begins execution. <\/p>\n Typically, there are three types of “advice” that can be weaved<\/strong> or attached to a join point: Before, After<\/em><\/strong> and Around<\/em><\/strong>. “Before” advice will execute just prior to the method to which it is attached, but cannot modify the execution of that method. That is, the “Before” advice cannot stop the execution of the method. “After” advice will execute directly proceeding the return from the method to which it is attached, and it can typically get access to the return value from the method.<\/p>\n “Around” advice is called before the method itself, and can<\/em> alter the behaviour of the method to which it is attached. Typically, this includes deciding whether or not the method should be invoked at all, or even modifying the arguments passed to it. Thus “Around” advice is the most powerful. <\/p>\n It should be noted that for AOP to be truly effective the invocation of the advice attached to a method\/join point must be transparent. That is, once the advice has been attached to a target object\/method, one should not have to invoke the target method in any special manner in order to get the advice to fire.<\/p>\n One other term to note is the pointcut<\/strong>. A pointcut is simply a predicate\/expression that selects a set of join points. Thus, by defining a pointcut, advice can be attached to multiple join points that meet\/match the pointcut’s expression. In fact, this is typically how AOP is modeled from a high-level point-of-view. When reaching a join point that matches a certain pointcut predicate, the advice associated with that pointcut is invoked.<\/p>\n But all of these explanations and terms may still be confusing without a concrete example, so for that we’ll take a look at the jQuery AOP<\/a> plugin. JavaScript (especially with jQuery) is not really a place where AOP is used heavily or needed, since the use of callbacks already provides some level of separation of concerns. Indeed, the Ajax Events<\/a> available for hooking into using jQuery already provide some sort of AOP-like functionality.<\/p>\n Having said that, the jQuery AOP plugin is quite easy to use. Here’s a quick example that allows you to keep track of the number of event handlers invoked:<\/p>\n Here, we attach advice around any global function whose name starts with “handle” and is followed by a camel-case name, such as It’s worthwhile to note that you must attach or “weave” the aspect to the function before<\/strong> binding the function any any events. This is because when you bind a function to an event, it is copied over by reference<\/a>. The jQuery AOP plugin essentially weaves advice to functions by creating a new function that includes both the advice and an invocation of the original function. However, if you do this after<\/em> binding the function to an event handler, the event handler will still refer to the original function<\/strong>, that is, the one without any advice attached to it!<\/p>\n AOP may have limited utility in JavaScript, as I’ve found, thanks to excellent JavaScript libraries such as jQuery. jQuery already achieves decent separation of concerns thanks to the many built-in callbacks, mainly for Ajax events. It also supports the use of custom events<\/a>, which may be used in a similar manner to some AOP advice types.<\/p>\nAOP’s goals<\/h2>\n
if (isUserAuthenticated())\r\n{\r\n items = getUserTodoList(getUserContext());\r\n foreach (items as item)\r\n {\r\n \/\/ Output each todo item to the page...\r\n }\r\n}\r\nelse\r\n{\r\n \/\/ Redirect to login page...\r\n}<\/code><\/pre>\n
Simplicity through Separation<\/h2>\n
AOP with jQuery<\/h2>\n
Site = new Object();\r\nSite.handlerInvokeCount = 0;\r\njQuery(function()\r\n{\r\n \/\/ Note: Must apply the advice to the function(s) BEFORE binding as an event\r\n \/\/ handler.\r\n jQuery.aop.around( {target: window, method: \/^handle[A-Z]\/}, \r\n function(invocation) {\r\n window.alert(\"Invoking `\" + invocation.method + \"`\");\r\n \r\n window.alert(\"Number of event handlers invoked so far: \" + ++Site.handlerInvokeCount);\r\n \r\n \/\/ Note: Can stop the invocation of the target method by *not* calling \r\n \/\/ proceed().\r\n return invocation.proceed();\r\n });\r\n \r\n jQuery(\"form\").submit(handleFormSubmission);\r\n\r\n});\r\n\r\nfunction handleFormSubmission(e)\r\n{\r\n e.preventDefault();\r\n window.alert(\"Inside handleFormSubmission\");\r\n}<\/code><\/pre>\n
handleFormSubmission<\/strong><\/code>. We don’t do anything interesting but increment and report the current count for the number of “handle” methods invoked. We then attach the
handleFormSubmission<\/code> to a form submission event.<\/p>\n
Conclusion<\/h2>\n