Presentation is loading. Please wait.

Presentation is loading. Please wait.

Aspect-Oriented Programming

Similar presentations


Presentation on theme: "Aspect-Oriented Programming"— Presentation transcript:

1 Aspect-Oriented Programming
The most recent programming paradigm, developed around 2001 In a way, its orthogonal to OOP The idea: you have some implementation that must stretch across units (classes, procedures) you implement it as an aspect the compiler then adds to the implementation of each unit your aspect Example: we have an OO-based windowing system we want to add a security component that ensures that resizing can only be done under certain circumstances rather than redefining all of our classes, we define the aspect and let the compiler insert the code into each appropriate class for us!

2 Cross-Cutting Aspects
We refer to aspects as cross-cutting because they cut across classes Consider the hierarchy to the right we want to add (or alter aspect1) rather than implement (or update) aspect1 in all classes, the compiler will do this for us with little effort on our part

3 How AOP Works Aspects are stand-alone modules containing three types of components inter-type declarations – variables that are added to the objects of the system advice – code that is added to the objects of the system along with where it should be added (at the start of a method, after, in an exception handler, etc) pointcut – the location(s) within the class that the advice can be applied pointcuts are defined as one or more join points that describe such things as types of methods, type of parameters passed to the methods, etc a pointcut might have multiple join points we can use regular expressions to be more generic about our join points (e.g., using * for any type of parameter) While we can have multiple aspects to add to an OOP system, multiple aspects (pieces of advice) are hard to automatically implement into a given class that is, having multiple aspects is not necessarily scalable

4 Pointcuts Pointcuts map advice to a location within the OO code
there might be a one-to-one mapping of advice to a given object there might be a one-to-many mapping of advice to a group of objects Join points can include invoked by constructor when object is constructed, calls to super start of method, end of method start of loop, exit of loop when a particular member is initialized, accessed, modified upon exception thrown or caught There are several types of pointcuts, here are three Kinded – match a particular kind of join point Dynamic – check runtime types and bind variables Scope – limit the scope by matching on some variable-based condition

5 Advice Can be specified to run at different times
before the join point code executes after the join point code executes in place of the join point code (known as “around”) only if the join point code throws an exception (known as “after throwing”) after the finally clause of a join point executes (known as after finally) note that since a finally clause always executes no matter if an exception is thrown or not, this type of advice runs automatically different combinations of the above can be applied such as around and after throwing

6 Weaving The goal of AOP is to simplify the programmer’s task so that an aspect can be added to an OOP system without having to re-implement multiple classes and yet the aspect must be added to a number of class definitions How? By weaving the aspect into the existing classes who does the weaving? the aspect weaver the aspect weaver takes OO code + aspects and combines them Weaving can produce either a new source program in the original language interpreted code to the interpreted environment where the OO code was already loaded into the environment and now the weaver adds the aspects without weaving, AOP is really just more OOP, it is the weaving aspect that makes AOP different

7 Example: Adding Logging
We have a banking system with classes handling withdraw, overdraw, deposit, balance, summary We add an aspect called logging to automatically log all actions For join points, we define them as around for withdraw/deposit after for the rest Advice differs because the specific text being logged will differ, but they will all be similar in that they will all open a text file output a message to the textfile messages will be similar but specialized and include the time/date, client’s name and success/failure of operation close the textfile

8 Example in AspectJ aspect Logger { pointcut method() : withdraw(* *(..)); before() : method() { logfile.println("User " + u + " is attempting a withdrawal of " + amount + " from bank account " + account); } after() : method() { if(...) logfile.println("Success"); else logfile.println("Failure"); The … in the if statement tests whatever condition is needed to determine success or failure

9 AspectJ An extension to Java that adds aspects, pointcuts, and advice
aspect FaultHandler { private boolean Server.disabled = false; private void reportFault() { System.out.println("Failure! Please fix it."); } public static void fixServer(Server s) { s.disabled = false; pointcut services(Server s): target(s) && call(public * *(..)); before(Server s): services(s) { if (s.disabled) throw new DisabledException(); after(Server s) throwing (FaultException e): services(s) { s.disabled = true; reportFault(); An extension to Java that adds aspects, pointcuts, and advice seems to be the most popular AOP language comes with an aspect weaver as part of the compiler/JVM Here is an example of an aspect implemented in AspectJ

10 Explanation The aspect starts with the word aspect and its name
This is followed by any inter-type declarations (Server.disabled here) Methods are then defined which will be invoked by the advice notice that one method is static in that it will be shared among all objects Next, we have a pointcut to define when the advice will be executed here, there is a single pointcut tying this aspect to the one class Server the pointcut has two pieces of advice, one to run before and one to run only after throwing an exception

11 Continued Let’s take a closer look at the code to understand it
pointcut services(Server s): target(s) && call(public * *(..)); The pointcut is named services the pointcut will occur when the object being interacted with is a Server and the Server is having any public method invoked the call(public * *(..)) means invoking a public method named * with any return type and any parameters (by type and number) the weaver will then add the advice to all public methods of the Server class The advice are two sets of code the if statement (for before) is added before any method call that is, if a method is to call a public method and disabled is true, then throw the exception the second advice is added to the exception handler of such methods where it resets disabled to true and calls reportFault()

12 More on AspectJ If you look back at the example, you will see that the inter-type declaration, methods and advice are all Java It is the pointcuts and the specification of join points that are new Pointcuts consist of call – when a method is called execution – when a method’s body is executed handler – when an exception handler executes this(type) – when the currently executing object is of the given type target(type) – when the referenced object is of the given type within – when the executing code belongs to a given class cflow – when the executing code is in the control flow of a specified method pointcuts can be combined using &&, ||, !

13 Advice The code in the advice starts with the join point (at what point in the given code the advice should execute) the advice is passed a parameter and if it is an after join point, it can specify a return type after(Object o) returning(int x): somepointcut(o) { … } note that x does not have to be part of the advice but instead it can be part of the method which the advice will be embedded into for after throwing, you can specify an exception type so that the advice only executes if the given type of exception is thrown

14 Example Pointcuts pointcut cflow(call(public * main(…)))&&(this(class2)||this(class3)) this pointcut identifies any point in the code where the executing object is of type class 2 or class 3 and it was reached from this class’ main pointcut example(Object1 o) : target(o) && call(* foobar(..)); this pointcut identifies for an object of type Object1, the method named foobar was called Let’s assume to the second pointcut we have the following advice after(Object1 o) throwing(Object1Exception e): example(o) {…} this advice only executes if the specific Object1Exception was thrown, any other form of exception thrown by o does not cause this advice to be invoked

15 Complete Example Original Java code public class Demo { static Demo d;
public static void main(String[] args){ new Demo().go(); } void go(){ d = new Demo(); d.foo(1,d); System.out.println(d.bar(new Integer(3))); void foo(int i, Object o){ System.out.println("Demo.foo(" + i + ", " + o + ")\n"); String bar (Integer j){ System.out.println("Demo.bar(" + j + ")\n"); return "Demo.bar(" + j + ")"; Original Java code

16 aspect GetInfo { static final void println(String s){ System.out.println(s); } pointcut goCut(): cflow(this(Demo) && execution(void go())); pointcut demoExecs(): within(Demo) && execution(* *(..)); Object around(): demoExecs() && !execution(* go()) && goCut() { println("Intercepted message: " + thisJoinPointStaticPart.getSignature().getName()); println("in: " + thisJoinPointStaticPart.getSignature().getDeclaringType().getName()); printParameters(thisJoinPoint); println("Running original method: \n" ); Object result = proceed(); println(" result: " + result ); return result; } static private void printParameters(JoinPoint jp) { println("Arguments: " ); Object[] args = jp.getArgs(); String[] names = ((CodeSignature)jp.getSignature()).getParameterNames(); Class[] types = ((CodeSignature)jp.getSignature()).getParameterTypes(); for (int i = 0; i < args.length; i++) { println(" " + i + ". " + names[i] + " : " types[i].getName() + " = " args[i]);


Download ppt "Aspect-Oriented Programming"

Similar presentations


Ads by Google