Report On Aspect Oriented Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

A Seminar report On ASPECT ORIENTED PROGRAMMING Submitted In Partial Fulfillment For The Award of the Degree Of BACHELOR OF TECHNOLGY

In Information Technology

Submitted To:
Mr. Shiv Kumar Agarwal Head Of Department Department Of I.T.

Submitted By:
Sudhanshu Mathur Roll no:IT08059

DEPARTMENT OF INFORMATION TECHNOLOGY JAIPUR ENGINEERING COLLEGE, KUKAS RAJASTHAN TECHNICAL UNIVERSITY

Jaipur Engineering College, Kukas, Jaipur


SESSION 2011-2012

CERTIFICATE
This is to certify that project entitled Aspect oriented programming, submitted by Sudhanshu Mathur, students of final year B.Tech in Information Technology, JAIPUR ENGINEERING COLLGE, KUKAS, JAIPUR was completed under my supervision and their work was found satisfactory and I found them sincere towards their work.

Signature Mr.Shiv Agarwal Head, Department of IT Place: - Jaipur Date: - 14/03/2012

Preface
This report intends to reflect some of the basics required for building a project i.e. Aspect oriented programming and related fundamentals. The total aspects have been formulated and presented on the basis of ideas and information gathered from emerging technology. This report has been written in response to a comprehensive study. The report mentions and evaluates the various aspects, through analysis of the various facts and figures. Accuracy and precision has been given prime consideration, while compiling the report.

ACKNOWLEDGEMENT

Let me in this page express my heartiest gratitude to all those who helped me in various stages of this study. I am very much thankful to Dr. G.D.SHARMA, Director (Academics), JEC College, Kukas, and Mr. Shiv Kumar Agarwal, HOD, Dept. Of IT for giving me permission to undergo the seminar and providing all other necessary facility. I would also thankful to Mr. Manoj Raman and Ms Anuradha, Sr. Faculty of IT department for their kind support. During the seminar period all the staff member of Deptt. have helped me with there skills. Here by I express my sincere thanks to seminar coordinator. Also I am thankful to other technical staff of the Deptt. who have helped me to complete my seminar successfully. I wish to express my deep sense of gratitude to my seminar guide for her valuable guidance and kind cooperation without which this project would have not been possible.

Sudhanshu Mathur (IT08059)


IT Department Jaipur Engineering College

INDEX

CHAPTER
1. 2

NAME OF THE CHAPTER


INTRODUCTION GOALS OF ASPECT ORIENTED PROGRAMMING TERMINOLOGY 3.1 CROSS CUTTING CONCERN S ASPECT ADVICE JOINPOINT POINTCUT 07

PAGE NO
02 04

07

3.2 3.3 3.4 3.5

08 08 09 10

OVERVIEW OF ASPECT ORIENTED PROGRAMMING ARCHITECTURE OF AOP MOTIVATION AND BASIC CONCEPTS ASPECT-J COMPARISION TO OTHER PROGRAMMING PARADIGMS ADVANTAGES & DISADVANTAGES CONCLUSION

11

5 6 7 8 9

13 14 17 22 23 24

10

ABSTRACT
In software engineering, the programming paradigms of Aspect- Oriented programming (AOP), and Aspect- Oriented Software development (AOSD) attempt to aid programmers in the separation of concerns, specifically cross-cutting concerns, as an advance in modularization. AOP does so using primarily language changes, while AOSD uses a combination of language, environment, and method. Separation of concerns entails breaking down a program into distinct parts that overlap in functionality as little as possible. All programming methodologies including procedural programming and object-oriented programming support some separation and encapsulation of concerns (or any area of interest or focus) into single entities. For example, procedures, packages, classes, and methods all help programmers encapsulate concerns into single entities. But some concerns defy these forms of encapsulation. Software engineers call these crosscutting concerns, because they cut across many modules in a program. Logging offers one example of a crosscutting concern, because a logging strategy necessarily affects every single logged part of the system. Logging thereby crosscuts all logged classes and methods. AOP is a new technology for separating crosscutting concerns into single units called aspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviour that affects multiple classes into reusable modules. Typically, an aspect is scattered or tangled as code, making it harder to understand and maintain. It is scattered by virtue of the function (such as logging) being spread over a number of unrelated functions that might use its function, possibly in entirely unrelated systems, different source languages, etc. That means to change logging can require modifying all affected modules. Aspects become tangled not only with the mainline function of the systems in which they are expressed but also with each other. That means changing one concern entails understanding all the tangled concerns or having some means by which the effect of changes can be inferred. Aspects emerged out of object-oriented programming and computational reflection. AOP languages have functionality similar to, but more restricted than metaobject protocols. Aspects relate closely to programming concepts like subjects, mixins, and delegation. Other ways to use aspect-oriented programming paradigms include Composition Filters and the hyperslices approach. Since at least the 1970s, developers have been using forms of interception and dispatch-patching that resemble some of the implementation methods for AOP, but these never had the semantics that the crosscutting specifications provide written in one place. Designers have considered alternative ways to achieve separation of code, such as C#'s partial types, but such approaches lack a quantification mechanism that allows reaching several join points of the code with one declarative statement.

CHAPTER 1 INTRODUCTION
Aspect Oriented Programming (AOP) is a promising new technology for separating crosscutting concerns that are usually hard to do in object-oriented programming . Now-a-days, object-oriented programming (OOP) has become the mainstream programming paradigm where real world problems are decomposed into objects that abstract behavior and data in a single unit.OOP encourages software re-use by providing design and language constructs for modularity, encapsulation, inheritance, and polymorphism. Although OOP has met great success in modelling and implementing complex software systems, it has its problems. Practical experience with large projects has shown that programmers may face some problems with maintaining their code because it becomes increasingly difficult to cleanly separate concerns into modules. An attempt to do a minor change in the program design may require several updates to a large number of unrelated modules. AOP is a new technology for separating crosscutting concerns into single units called aspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviors that affect multiple classes into reusable modules. With AOP, we start by implementing our project using our OO language (for example, Java), and then we deal separately with crosscutting concerns in our code by implementing aspects. Finally, both the code and aspects are combined into a final executable form using an aspect weaver. As a result, a single aspect can contribute to the implementation of a number of methods, modules, or objects, increasing both reusability and maintainability of the code. In computing, Aspect-oriented-programming (AOP) is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns. AOP forms a basis for aspect-oriented software development. AOP includes programming methods and tools that support the modularization of concerns at the level of the source code, while "aspect-oriented software development" refers to a whole engineering discipline. Question arises that what actually computing is and what we have to do for that. Computing is usually defined as the activity of using and improving computer hardware and software. It is the computer-specific part of information technology. Computer science (or computing science) is the study and the science of the theoretical foundations of information and computation and their implementation and application in computer systems. Aspect-oriented programming entails breaking down program logic into distinct parts (socalled concerns, cohesive areas of functionality). Nearly all programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing abstractions (e.g., procedures, modules, classes, methods) that can be used for implementing, abstracting and composing these concerns. But some concerns defy these forms of implementation and are called crosscutting concerns because they "cut across" multiple abstractions in a program.

Logging exemplifies a crosscutting concern because a logging strategy necessarily affects every logged part of the system. Logging thereby crosscuts all logged classes and methods. All AOP implementations have some crosscutting expressions that encapsulate each concern in one place. The difference between implementations lies in the power, safety, and usability of the constructs provided. For example, interceptors that specify the methods to intercept express a limited form of crosscutting, without much support for type-safety or debugging. AspectJ has a number of such expressions and encapsulates them in a special class, an aspect. For example, an aspect can alter the behavior of the base code (the nonaspect part of a program) by applying advice (additional behavior) at variousjoin points (points in a program) specified in a quantification or query called a pointcut (that detects whether a given join point matches). An aspect can also make binary-compatible structural changes to other classes, like adding members or parents. Starting from or! and other primitive filters, the programmer could work up to the definition of a filter that selects just those black pixels on a horizontal edge, returning a new image consisting of just those boundary pixels.

functionality
pixelwise logical operations shift image up, down difference of two images

implementation
written using loop primitive as above written using loop primitive; slightly different loop structure (defun remove! (a b) (and! a (not! b))) (defun top-edge! (a) (remove! a (down! a))) (defun bottom-edge! (a) (remove! a (up! a))) (defun horizontal-edge! (a) (or! (top-edge! a) (bottom-edge! a)))

pixels at top edge of a region

pixels at bottom edge of a region

horizontal edge pixels

CHAPTER 2 GOALS OF AOP


Aspect-oriented programming (AOP) better separates concerns than previous methodologies, thereby providing modularization of crosscutting concerns. In the early days of computer science, developers wrote programs by means of direct machine-level coding. Unfortunately, programmers spent more time thinking about a particular machine's instruction set than the problem at hand. Slowly, we migrated to higherlevel languages that allowed some abstraction of the underlying machine. Then came structured languages; we could now decompose our problems in terms of the procedures necessary to perform our tasks. However, as complexity grew, we needed better techniques. Object-oriented programming (OOP). Let us view a system as a set of collaborating objects. Classes allow us to hide implementation details beneath interfaces. Polymorphisms provided a common behavior and interface for related concepts, and allowed more specialized components to change a particular behaviour without needing access to the implementation of base concepts. Programming methodologies and languages define the way we communicate with machines. Each new methodology presents new ways to decompose problems: machine code, machine-independent code, procedures, classes, and so on. Each new methodology allowed a more natural mapping of system requirements to programming constructs. Evolution of these programming methodologies let us create systems with ever increasing complexity. The converse of this fact may be equally true: we allowed the existence of ever more complex systems because these techniques permitted us to deal with that complexity. Aspect-oriented programming (AOP) better separates concerns than previous methodologies, thereby providing modularization of crosscutting concerns.

Good modularity XML parsing

Figure 1
URL pattern matching in org.apache.tomcat
red shows relevant lines of code nicely fits in two boxes (using inheritance)

Good modularity URL pattern matching

Figure 2
URL pattern matching in org.apache.tomcat
red shows relevant lines of code nicely fits in two boxes (using inheritance)

Implications of Non-modularization
Redundant code
same fragment of code in many places

Difficult to reason about


non-explicit structure the big picture of the tangling isnt clear

Difficult to change
have to find all the code involved and be sure to change it consistently and be sure not to break it by accident

CHAPTER 3 TERMINOLOGY
Before we delve too deeply into AOP, let's introduce some terminology to help us understand the concepts. Cross-cutting concerns: Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though the primary functionality of each class is very different, the code needed to perform the secondary functionality is often identical.

Advice: This is the additional code that you want to apply to your existing model. In our
example, this is the logging code that we want to apply whenever the thread enters or exits a method.

Point-cut: This is the term given to the point of execution in the application at which crosscutting concern needs to be applied. In our example, a point-cut is reached when the thread enters a method, and another point-cut is reached when the thread exits the method.

Aspect: The combination of the point-cut and the advice is termed an aspect. In the example
below, we add a logging aspect to our application by defining a point-cut and giving the correct advice. Aspects should have the following properties: robust (change to one aspect should have a limited impact on other aspects), systemic (they affect the target program at many different places), cross-cutting each other (in the target program information about one aspect is mixed with information about other aspects), loosely coupled (an aspect should not know the details of other aspects), contain join points (which are used to combine the aspects).

CROSS- CUTTING CONCERNS


Separation of concerns entails breaking down a program into distinct parts that overlap in functionality as little as possible. All programming methodologies including procedural programming and object-oriented programming support some separation and encapsulation of concerns (or any area of interest or focus) into single entities. For example, procedures, packages, classes, and methods all help programmers encapsulate concerns into single entities. But some concerns defy these forms of encapsulation. Software engineers call these crosscutting concerns, because they cut across many modules in a program. An example of crosscutting concerns is "logging," which is frequently used in distributed applications to aid debugging by tracing method calls. Suppose we do logging at both the beginning and the end of each function body. This will result in crosscutting all classes that have at least one function. Other typical crosscutting concerns include context-

sensitive error handling, performance optimization, and design patterns. Crosscutting concerns may exist in some programs, especially large ones. However, in some situations, redesign of the system might transform a crosscutting into an object. AOP assumes that crosscutting concerns may exist in programs and can't be re-factored out of the design in all situations.

ASPECT
Any AOP language has some crosscutting expressions that encapsulate the concern in one place. The difference between AOP languages lies in the power, safety, and usability of the constructs provided. E.g., interceptors that specify the methods to intercept express a limited form of crosscutting, without much support for type-safety or debugging. AspectJ has a number of such expressions and encapsulates them in a special class, an aspect. For example, an aspect can alter the behaviour of the base code (the non-aspect part of a program) by applying advice (additional behaviour) at various join points (points in a program) specified in a quantification or query called a pointcut (that detects whether a given join point matches). An aspect can also make binary- compatible structural changes to other classes, like adding members or parents. Many AOP languages support method executions and field references as join points. In them the developer can write a pointcut to match, for example, all field-set operations on specific fields, and code to run when the field is actually set. Some also support things like defining a method in an aspect on another class. AOP languages can be compared based on the join points they expose, the language they use to specify the join points, the operations permitted at the join points, and the structural enhancements that can be expressed. When thinking of an object and its relationship to other objects we often think in terms of inheritance. We define some abstract class; let us use a Dog class as an example. As we identify similar classes but with unique behaviours of their own, we often use inheritance to extend the functionality. For instance, if we identified a Poodle we could say a Poodle Is A Dog, so Poodle inherits Dog. So far so good, but what happens when we define another unique behaviour later on that we label as an Obedient Dog? Surely not all Dogs are obedient, so the Dog class cannot contain the obedience behaviour. Furthermore, if we were to create an Obedient Dog class that inherited from Dog, then where would a Poodle fit in that hierarchy? A Poodle is A Dog, but a Poodle may or may not be obedient; does Poodle, then, inherit from Dog, or does Poodle inherit from Obedient Dog? Instead, we can look at obedience as an aspect that we apply to any type of Dog that is obedient, as opposed to inappropriately forcing that behaviour in the Dog hierarchy. In software terms, aspect-oriented programming allows us the ability to apply aspects that alter behavior to classes or objects independent of any inheritance hierarchy. We can then apply these aspects either during runtime or compile time.

ADVICE
Advice is a way of expressing a cross cutting action that needs to occur. Now that the aspect has defined the points it should log, it uses advice to accomplish the actual logging. Advice is code that executes before, after, or around a join point. You define advice relative to a pointcut, saying something like "run this code after every method call I want to log." Hence the advice is the action taken by an aspect at a particular join point. Different types of advice

include around", "before" and "after" advice.

Types of advice:
Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception). After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception. After throwing advice: Advice to be executed if a method exits by throwing an exception. After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return). Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behaviour before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception. Around advice is the most general kind of advice.

JOINPOINT
Join point is a point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. Join point information is available in advice bodies by declaring a parameter of type : aspectJ. lang. JoinPoint. Joinpoint is the well defined points in code that can be identified. Think of a joinpoint as a defined point in program flow. A good example of a joinpoint is the following: when code invokes a method, that point at which that invocation occurs is considered the join point. The pointcut allows us to specify or define the joinpoints that we wish to intercept in our program flow. A Pointcut also contains an advice that is to occur when the joinpoint is reached. So if we define a Pointcut on a particular method being invoked, when the invocation occurs or the joinpoint is invoked, it is intercepted by the AOP framework and the pointcut's advice is executed. An advice can be several things, but you should most commonly think of it as another method to invoke. So when we invoke a method with a pointcut, our advice to execute would be another method to invoke. This advice or method to invoke could be on the object whose method was intercepted.

Join point models


The advice-related component of an aspect-oriented language defines a join point model (JPM). A JPM defines three things: When the advice can run: These are called join points because they are points in a running program where additional behavior can be usefully joined. A join point needs to be addressable and understandable by an ordinary programmer to be useful. (It should also be stable across inconsequential program changes in order for an aspect to be stable across such changes.) A way to specify (or quantify) join points, called point cuts. Pointcuts determine whether a given join point matches. Most useful pointcut languages use a syntax like the base language (e.g., Java signatures are used for AspectJ) and allow reuse through naming and combination.

A means of specifying code to run at a join point: In AspectJ, this is called advice, and can run before, after, and around join points.

POINT- CUT
Point- cut is a way of specifying a Joinpoint by some means of configuration or code. Pointcut is a predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP: Spring uses the AspectJ pointcut language by default. The pointcut allows us to specify or define the joinpoints that we wish to intercept in our program flow. A Pointcut also contains an advice that is to occur when the joinpoint is reached. So if we define a Pointcut on a particular method being invoked, when the invocation occurs or the joinpoint is invoked, it is intercepted by the AOP framework and the pointcut's advice is executed. An advice can be several things, but you should most commonly think of it as another method to invoke. So when we invoke a method with a pointcut, our advice to execute would be another method to invoke. This advice or method to invoke could be on the object whose method was intercepted.

SOME POINTS
CUT DESIGNATORS
execution - for matching method execution join points, this is the primary pointcut designator you will use when working with Spring AOP. within - limits matching to join points within certain types (simply the execution of a method declared within a matching type when using Spring AOP) this - limits matching to join points (the execution of methods when using Spring AOP) where the bean reference (Spring AOP proxy) is an instance of the given type. target - limits matching to join points (the execution of methods when using Spring AOP) where the target object (application object being proxied) is an instance of the given type. args - limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types target - limits matching to join points (the execution of methods when using Spring AOP) where the class of the executing object has an annotation of the given type. args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type. annotation - limits matching to join points where the subject of the join point (method being executed in Spring AOP) has the given annotation.

CHAPTER 4 OVERVIEW OF AOP


When Object-Oriented (OO) programming entered the mainstream of software development, it had a dramatic effect on how software was developed. Developers could visualize systems as groups of entities and the interaction between those entities, which allowed them to tackle larger, more complicated systems and develop them in less time than ever before. The only problem with OO programming is that it is essentially static, and a change in requirements can have a profound impact on development timelines. AspectOriented Programming (AOP) complements OO programming by allowing the developer to dynamically modify the static OO model to create a system that can grow to meet new requirements. Just as objects in the real world can change their states during their lifecycles, an application can adopt new characteristics as it develops. Consider an example: many of you have developed simple web applications that use servlets as the entry point, where a servlet accepts the values of a HTML form, binds them to an object, passes them into the application to be processed, and then returns a response to the user. The first cut of the servlet may be very simple, with only the minimum amount of code required to fulfill the use case being modeled. The code, however, often inflates to three to four times its original size by the time secondary requirements such as exception handling, security, and logging have been implemented. I use the term "secondary requirements" because a servlet should not need to know about the logging or security mechanisms being used; its primary function is to accept input and process it. AOP allows us to dynamically modify our static model to include the code required to fulfill the secondary requirements without having to modify the original static model (in fact, we don't even need to have the original code). Better still, we can often keep this additional code in a single location rather than having to scatter it across the existing model, as we would have to if we were using OO on its own. Programs are decomposed into suitable cross-cutting building blocks, i.e. a building block affects many parts of the combined program. Building blocks which contain redundant information are over specified and need to be reduced to a description which removes the overspecification. The reduced description is expressed in an aspect description language. This leads to a solution of a more general problem while at the same time removing the redundancy from the program. The reduced building blocks need to be compiled together into the original or an improved form of the original program. An important issue is how the reduced descriptions collaborate. They need to refer to a common vocabulary (join points) so that the compiler can regenerate the original program. To understand a program, we need to understand the aspects underlying the program. To avoid manual aspect extrication and to ease evolution, it is better to express the aspects directly. Evolution is simplified, since changes to aspects are localized to an aspect description rather than spread out through a program. Aspects should have the following properties: robust (change to one aspect should have a limited impact on other aspects), systemic (they affect the target program at many different places), cross-cutting

each other (in the target program information about one aspect is mixed with information about other aspects), loosely coupled (an aspect should not know the details of other aspects), contain join points (which are used to combine the aspects).

Join point models


The advice-related component of an aspect-oriented language defines a join point model (JPM). A JPM defines three things: 1. When the advice can run. These are called join points because they are points in a running program where additional behavior can be usefully joined. A join point needs to be addressable and understandable by an ordinary programmer to be useful. It should also be stable across inconsequential program changes in order for an aspect to be stable across such changes. Many AOP implementations support method executions and field references as join points. 2. A way to specify (or quantify) join points, called pointcuts. Pointcuts determine whether a given join point matches. Most useful pointcut languages use a syntax like the base language (for example, AspectJ uses Java signatures) and allow reuse through naming and combination. 3. A means of specifying code to run at a join point. AspectJ calls this advice, and can run it before, after, and around join points. Some implementations also support things like defining a method in an aspect on another class.

CHAPTER 5 ARCHITECTURE OF ASPECT ORIENTED PROGRAMMING

Figure 3

CHAPTER 6 MOTIVATION AND BASIC CONCEPTS


Some code is scattered or tangled, making it harder to understand and maintain. It is scattered when one concern (like logging) is spread over a number of modules (e.g., classes and methods). That means to change logging can require modifying all affected modules. Modules end up tangled with multiple concerns (e.g., account processing, logging, and security). That means changing one module entails understanding all the tangled concerns. For example, consider a banking application with a conceptually very simple method for transferring an amount from one account to another: However, in a real-world banking application, this transfer method seems far from adequate. It requires security checks to verify that the current user has the authorization to perform this operation. The operation should be in a database transaction in order to prevent accidental data loss. For diagnostics, the operation should be logged to the system log. And so on. The code has lost its elegance and simplicity because the various new concerns have become tangled with the basic functionality (sometimes called the business logic concern). Transactions, security, and logging all exemplify cross-cutting concerns. (This particular example may not be the best as this represents a failure to properly factor classes: a transfer should be its own object.) Also consider what happens if we suddenly need to change (for example) the security considerations for the application. In the program's current version, security-related operations appear scattered across numerous methods, and such a change would require a major effort. Therefore, we find that the cross-cutting concerns do not get properly encapsulated in their own modules. This increases the system complexity and makes evolution considerably more difficult. AOP attempts to solve this problem by allowing the programmer to express cross-cutting concerns in stand-alone modules called aspects. Aspects can contain advice (code joined to specified points in the program) and inter-type declarations (structural members added to other classes). For example, a security module can include advice that performs a security check before accessing a bank account. The pointcut defines the times (join points) that a bank account can be accessed, and the code in the advice body defines how the security check is implemented. That way, both the check and the places can be maintained in one place. Further, a good pointcut can anticipate later program changes, so if another developer creates a new method to access the bank account, the advice will apply to the new method when it executes.

AOP concepts
Let us begin by defining some central AOP concepts. Unfortunately, AOP terminology is not particularly intuitive; however, it would be even more confusing if spring used its own terminology.

Aspect: A modularization of a concern that cuts across multiple objects. Transaction


management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the Aspect annotation AspectJ style).

Join point: A point during the execution of a program, such as the execution of a
method or the handling of an exception. In Spring AOP, a join point always represents a method execution. Join point information is available in advice bodiesby declaring a parameter of type aspectj.lang.JoinPoint.

Advice: Action taken by an aspect at a particular join point. Different types of


advice include "around," "before" and "after" advice. Advice types are discussed below. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point.

Pointcut: A predicate that matches join points. Advice is associated with a


pointcut expression and runs at any join point matched by the pointcut (for example, the execution of a method with a certain name). The concept of join points as matched by pointcut expressions is central to AOP: Spring uses the AspectJ pointcut language by default.

Introduction: (Also known as an inter-type declaration). Declaring additional methods


or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any proxied object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching.

Target object: Object being advised by one or more aspects. Also referred to as
the advised object. Since Spring AOP is implemented using runtime proxies, this object will always be a proxied object.

AOP proxy: An object created by the AOP framework in order to implement the
aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy. Proxy creation is transparent to users of the schema-based and AspectJ styles of aspect declaration introduced in Spring 2.0.

Weaving: Linking aspects with other application types or objects to create an advised
object. This can be done at compile time (using the AspectJ compiler, for example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

Aspect Weaver
AOP is a new technology for separating crosscutting concerns into single units called aspects. An aspect is a modular unit of crosscutting implementation. It encapsulates behaviours that affect multiple classes into reusable modules. With AOP, we start by implementing our project using our OO language (for example, Java), and then we deal separately with crosscutting concerns in our code by implementing aspects. Finally, both the code and aspects are combined into a final executable form using an aspect weaver. As a result, a single aspect can contribute to the implementation of a number of methods, modules, or objects, increasing both reusability and maintainability of the code. Figure explains the weaving process. It should note that the original code doesn't need to know about any functionality the aspect has added; it needs only to be recompiled without the aspect to regain the original functionality.

Figure 4

CHAPTER 7 ASPECTJ
Aspect Oriented Programming and Java
AOP is a concept, so it is not bound to a specific programming language. In fact, it can help with the shortcomings of all languages (not only OO languages) that use single, hierarchical decomposition. AOP has been implemented in different languages (for example, C++, Smalltalk, C#, C, and Java). Of course, the language that gains a great interest of the research community is the Java language.

The following is a list of tools that support AOP with Java:


AspectJ Aspect-Werkz Hyper/J JAC JMangler MixJuice PROSE ArchJava AspectJ, created at Xerox PARC, was proposed as an extension of the Java language for AOP. Join points, Pointcut, Advice, and Introduction -Where the tools of OOP are inheritance, encapsulation, and polymorphism, the components of AOP are join points, pointcut, advice, and introduction. For a better understanding of these new terms, let's consider the following simple example. public class TestClass { public void sayHello () { System.out.println ("Hello, AOP"); } public void sayAnyThing (String s) { System.out.println (s); } public static void main (String[] args) { sayHello (); sayAnyThing ("ok"); } } Listing 1: TestClass.java Now, we have our existing Java code in TestClass.java. Let's assume that we want to use aspects to do the following modifications: We would like to print a message before and after any call to the TestClass.sayHello() method.

We need to test that the argument of the TestClass.sayAnyThing() method is at least three characters. The following list is the AspectJ implementation. 1: public aspect MyAspect { 2: public pointcut sayMethodCall (): call (public void TestClass.say*() ); 3: public pointcut sayMethodCallArg (String str): call (public void TestClass.sayAnyThing (String)) && args(str); 4: before(): sayMethodCall() { 5: System.out.println("\n TestClass." + thisJoinPointStaticPart.getSignature().getName() + "start..." ); 6: } 7: after(): sayMethodCall() { 8: System.out.println("\n TestClass." + thisJoinPointStaticPart.getSignature().getName() + " end..."); 9: } 10: before(String str): sayMethodCallArg(str) { 11: if (str .length() < 3) { 12: System.out.println ("Error: I can't say words less than 3 characters"); 13: return; 14: } 15: } 16: } Listing 2: MyAspect.aj Line 1 defines an aspect in the same way we define a Java class. Like any Java class, an aspect may have member variables and methods. In addition, it may include pointcuts, advices, and introductions. In Lines 2 and 3, we specify where in the TestClass code our modification will take place. In AspectJ terms, we define two pointcuts. To explain what a pointcut means, we first need to define join points. Join points represent well-defined points in a program's execution. Typical join points in AspectJ include method/constructor calls, method/constructor execution, field get and set, exception handler execution, and static and dynamic initialization. In our example, we have two join points: the call to TestClass.sayHello and TestClass.sayAnyThing methods. Pointcut is a language construct that picks out a set of join points based on defined criteria. The criteria can be explicit function names, or function names specified by wildcards. public pointcut sayMethodCall (): call( public void TestClass.say*() ); In the preceding line, we define a pointcut, named sayMethodCall, that picks out any call to the TestClass.sayHello method. Moreover, it picks out any public TestClass method with zero arguments and a name that starts with "say" (for example, TestClass.sayBye). Pointcuts are used in the definition of advice. An advice in AspectJ is used to define additional code to be executed before, after, or around join points. In our example, Lines 4 and 7 define two advices that will be executed before and after the first pointcut. Finally, Lines 10-

15 implement an advice associated with the second pointcut and are used to set a precondition before the execution of the TestClass.sayAnyThing method.Whereas pointcuts and advice let you affect the dynamic execution of a program, introduction allows aspects to modify the static structure of a program. By using introduction, aspects can add new methods and variables to a class, declare that a class implements an interface, or convert checked to unchecked exceptions.

AspectJ Compiler
Initially, you have to download the most recent version of AspectJ, available for free at its official site and install it. Compiling and running our example is very easy. Just write: ajc MyAspect.aj TestClass.java java TestClass You should note that the source code at TestClass.java didn't change. To return to the original functionality of your program, just use your Java compiler to re-compile it. Developing with AspectJ Now that you have better sense of what aspect code looks like, let's turn our attention briefly to the business of writing aspects. In other words, let's answer the question, "How can I get the above code to work?" For aspects to affect regular class-based code, the aspects must be woven into the code they modify. To do this using AspectJ, you must compile your class and aspect code with the ajc compiler. ajc can operate either as a compiler or a precompiler, generating either valid .class or .java files, which you can then compile and run in any standard Java environment (with the addition of a small run-time JAR). To compile with AspectJ, you will need to explicitly specify the source files (both aspect and class) that you want to include in a given compilation -- ajc does not simply search your class path for relevant imports the way javac does. This makes sense because each class in a standard Java application acts as a somewhat isolated component. A class needs only the presence of classes that it directly references in order to operate correctly. Aspects represent aggregate behaviours that span multiple classes. Therefore, an AOP program needs to be compiled as a unit rather than one class at a time. By specifying the files that are included in a given compilation, you can also plug and unplug various aspects of your system at compile time. For instance, by including or excluding the logging aspect described earlier from a compilation, the application builder can add or remove method tracing from the Cactus framework. An important limitation to the current version of AspectJ is that its compiler can only weaver aspects into code for which it has the source. In other words, you cannot use ajc to add advice to precompiled classes. The AspectJ team regards this limitation as temporary, and the AspectJ Web site promises that a future version (officially 2.0) will allow byte code modification.

Tool support
Several development tools are included as part of AspectJ's release. This bodes well for AspectJ's future, because it indicates a strong commitment on the part of the authors to making AspectJ friendly to developers. Tool support is particularly important for an aspectoriented system because program modules can be affected by other modules of which they have no knowledge. One of the most important tools released with AspectJ is a graphical structure browser that reveals at a glance how aspects interact with other system components. This structure

browser is available as a plug-in for popular IDEs as well as a stand-alone tool. Other Spring aspects for AspectJ. In addition to the Configurable support, spring-aspects.jar contains an AspectJ aspect that can be used to drive Spring's transaction management for types and methods annotated with the Transactional annotation. This is primarily intended for users who want to use Spring's transaction support outside of the Spring container. The aspect that interprets Transactional annotations is the Annotation Transaction Aspect. When using this aspect, you must annotate the implementation class (and/or methods within that class), not the interface (if any) that the class implements. AspectJ follows Java's rule that annotations on interfaces are not inherited. A Transactional annotation on a class specifies the default transaction semantics for the execution of any public operation in the class. A Transactional annotation on a method within the class overrides the default transaction semantics given by the class annotation (if present). Methods with public, protected, and default visibility may all be annotated. Annotating protected and default visibility methods directly are the only way to get transaction demarcation for the execution of such operations.

Aspect-Oriented Programming in Java


Object oriented programming has become main stream over the last years, having almost completely replaced the procedural approach. One of the biggest advantages of object orientation is that a software system can be seen as being built of a collection of discrete classes. Each of these classes has a well defined task, its responsibilities are clearly defined. In an OO application, those classes collaborate to achieve the application's overall goal. However, there are parts of a system that cannot be viewed as being the responsibility of only one class, they cross-cut the complete system and affect parts of many classes. Examples might be locking in a distributed application, exception handling, or logging method calls. Of course, the code that handles these parts can be added to each class separately, but that would violate the principle that each class has well-defined responsibilities. This is where AOP comes into play: AOP defines a new program construct, called an aspect, which is used to capture cross-cutting aspects of a software system in separate program entities. The application classes keep their well-defined responsibilities. Additionally, each aspect captures cross-cutting behaviour.

CALLING PROCEDURES

Figure 5

CHAPTER 8 COMPARISION TO OTHER PROGRAMMING PARADIGMS


Aspects emerged out of object-oriented programming and computational reflection. AOP languages have functionality similar to, but more restricted than meta object protocols. Aspects relate closely to programming concepts like subjects, mixins, and delegation. Other ways to use aspect-oriented programming paradigms include Composition Filters and the hyperslices approach. Since at least the 1970s, developers have been using forms of interception and dispatch-patching that are similar to some of the implementation techniques for AOP, but these never had the semantics that the crosscutting specifications were written in one place. Designers have considered alternative ways to achieve separation of code, such as C#'s partial types, but such approaches lack a quantification mechanism that allows reaching several join points of the code with one declarative statement.

Procedural programming
In procedure oriented programming the main program is divided in to different and distinct functions and also they are programmed in to separate modules. The execution can be in a particular sequence. It follows a top- down approach for program execution. Execution in a given sequence FORTRAN, C, COBOL

Functional programming
In functional programming the program execution is through different well defined functions. If any function require any additional task it includes another sub functions. Evaluating a function Lisp, ML

Logic programming
In logic programming the program execution based on certain logics. Proving a theorem for Prolog

Object-oriented programming (OOP)


In object- oriented programming all the real world problems are decomposed in to different entities called objects. Objects are the basic run time entities of a program. Organizing a set of objects Smalltalk, Java, C++ (to some extent).

Aspect-oriented programming (AOP)


In AOP aspects are run at certain join points specified in the program. Execution based on certain behaviours AspectJ (a Java extension) Complements OOP ASPECT ORIENTED. Class code unit that encapsulates methods and attributes. Aspect code unit that encapsulates Pointcuts, advice, and attributes. Method signatures define the entry points for the execution of method bodies. Pointcut define the set of entry points (triggers) in which advice is executed. Method bodies implementations of the primary concerns. Advice implementations of the cross cutting concerns. Compiler converts source code into object code. Weaver instruments code (source or object) with advice.

CHAPTER 9 ADVANTAGES AND DISADVANTAGES OF AOP


ADVANTAGES:
The major advantages while using the AOP are follows: 1.) It improves the tractability of the program. 2.) It can be used for developing simpler and cleaner code. 3.) The code can be reusable and therefore reduce the redundancy of code. 4.) It is more easy to maintain than other programming languages. This advantage of AOP helps the programmers for developing more powerful softwares.

DISADVANTAGES:
Although AOP has several advantages it has some disadvantages. 1.) It is difficult to understand software because of invisibly injected aspects. 2.) It has fragile build problems. 3.) It has a complicated control flow breakage. 4.) There may be a chance for reduce quality of software if aspects are not appropriately managed.

CHAPTER 10 CONCLUSION
Programs are decomposed into suitable cross-cutting building blocks, i.e. a building block affects many parts of the combined program. Building blocks which contain redundant information are overspecified and need to be reduced to a description which removes the overspecification. The reduced description is expressed in an aspect description language. This leads to a solution of a more general problem while at the same time removing the redundancy from the program. The reduced building blocks need to be compiled together into the original or an improved form of the original program. An important issue is how the reduced descriptions collaborate. They need to refer to a common vocabulary (join points) so that the compiler can regenerate the original program."Aspect Oriented Programming", further, does provide a methodology, or at least as much a one as Object Oriented (which is, admittedly, scattered across such things as closures, classes, prototypes, etc.). If you read into Aspect Oriented, you'll learn that the methodology consists of: (a) Identifying from the language the places that modifications may be performed (join points). (b) A means of specifying which code to modify or where to add code (pointcuts), a means of specifying the modification to perform (advice or inter-type declarations depending on whether the code is 'run' or not). We got a different approach about programming paradigms which can be essentially used in frequent manner around the worlds best technologies.

You might also like