Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

Programming using Aspects

Authors: 1. Saurabh Saxena 2. Meena Kumar Assistant Professor, DIRD Delhi Assistant Professor, DIRD Delhi E-mail: [email protected] e-mail: [email protected]

Abstract :

We can define an ‘Aspect oriented programming’ as executing the code whenever a program shows certain behaviors. Aspects are an additional unit of modularity. Aspects can be reused. By reducing code tangling it makes it easier to understand what the core functionality of a module is. An “aspect weaver” takes the aspects and the core modules and composes the final system.

Volume-2 | Issue-3 | March,2015 | Paper-13 87 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

Abstract :

We can define an ‘Aspect oriented  Proving a theorem by programming’ as executing the code finding values for the free whenever a program shows certain variables behaviors. Aspects are an additional unit  Prolog, Haskell of modularity. Aspects can be reused. By  Object-oriented programming reducing code tangling it makes it easier (OOP) to understand what the core  Organizing a set of functionality of a module is. An “aspect objects, each with its own weaver” takes the aspects and the core set of responsibilities modules and composes the final system.  Smalltalk, Java, C++ (to some extent) Introduction  Aspect-oriented programming In the evolution age of computers where (AOP) every one is almost dependent on  Executing code whenever computers for various tasks, there is a a program shows certain big challenge for software developers to behaviors provide the tools that meet the  AspectJ (a Java requirement of the layman and of course, extension) the security to his valuable data.  Does not replace O-O From the beginning of this changing era, programming, but rather there are many paradigms in complements it programming according to the technological changes. These Programming using Aspects programming paradigms can be OOPS is considered as a security tool for data as classified as :- it provide the ‘data hiding’ from the external . users. Everything in OOPS is organized in  Procedural programming objects and each object has its own data and  Executing a set of functions to work on. Programming languages commands in a given like JAVA, C++ etc provide a very smart way to sequence do the things but there are certain anomalies to  Fortran, C, Cobol OOPS as:-  Functional programming a) Some programming tasks cannot  Evaluating a function be neatly encapsulated in objects, defined in terms of other but must be scattered throughout functions the code. Some of the tasks are :-  Lisp  Logic programming

Volume-2 | Issue-3 | March,2015 | Paper-13 88 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

 Logging (tracking – System wide concerns program behavior to a that span multiple file) modules.  Profiling (determining – Cuts across the typical where a program spends division of responsibility. its time) • OOP creates a coupling between  Tracing (determining core and crosscutting concerns. what methods are called • AOP aims to modularize when) crosscutting concerns.  Session tracking, session expiration The cross cutting concerns can be  Special security explained using an example as:- management Let consider the UML for a simple b) The result is crosscutting code-- figure editor in which there are two the necessary code “cuts across” concrete classes of figure element, many different classes and points and lines. The concern that the methods screen manager should be notified The cross cutting has the following whenever a figure element moves. consequences: - This requires every method that --- Redundant code moves a figure element to do the --- Difficult to reason about notification. --- Non-explicit structure --- The big picture of the Now we can define the core of aspect tangling isn’t clear oriented programming i.e ‘aspects’. --- Difficult to change An ‘aspect’ can be understood as:- --- Have to find all the code It is a modular units that cross-cut the involved... structure of other modular units. It is --- and be sure to change it defined in terms of partial information consistently from other units. It exist in both design --- and be sure not to break it and implementation phases. by accident --- Inefficient when crosscutting Also we can define an ‘Aspect oriented code is not needed programming’ as • In AOP crosscutting concerns are There are various crosscutting concerns implemented in aspects instead as:- of fusing them into core modules. • AOP addresses behaviors that • Aspects are an additional unit of span many, often unrelated, modularity. modules. • Aspects can be reused. • Core Concerns: • By reducing code tangling it – Primary core makes it easier to understand functionality. what the core functionality of a – Central functionality of a module is. module. • An “aspect weaver” takes the • Crosscutting Concerns: aspects and the core modules and composes the final system.

Volume-2 | Issue-3 | March,2015 | Paper-13 89 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

The ‘weaving’ is a set of rules that specify how to integrate the final system. A named “move’ that It can be implemented in various ways: chooses various method calls: – Source to source translation. pointcut move(): – Byte code enhancement, call(void FigureElement.setXY(int,int)) first compile source with || call(void Point.setX(int)) original , then || call(void Point.setY(int)) weave aspects into class || call(void Line.setP1(Point)) files. || call(void Line.setP2(Point)); – Just-in-time weaving done by a class loader. – By the language (code) compiler. //that runs before the move pointcut: The JAsCo language supports runtime before (): move() weaving and unweaving. { System.out.println("About to move"); Terminology used for ‘Aspects’ } The terminology used for AOP may // Advice that runs after the move contain the following:- pointcut: 1) after(): move() 2) Point cut { 3) Advice System.out.println("Just successfully 4) Introduction moved"); 5) Aspect } The brief introduction of all these is:- ---- A join point is a well-defined point Join Point in the program flow  A join point is a well-defined ---- A point cut is a group of join point in the program flow points  We want to execute some ---- Advice is code that is executed at a code (“advice”) each time point cut a join point is reached ---- Introduction modifies the members  We do not want to clutter of a class and the relationships up the code with explicit between classes indicators saying “This is ---- An aspect is a module for handling a join point” crosscutting concerns  AspectJ provides a syntax ---- Aspects are defined in terms of point for indicating these join cuts, advice, and introduction points “from outside” the ---- Aspects are reusable and actual code inheritable  A join point is a point in the ---- Each of these terms will be program flow “where something discussed in greater detail happens”  Examples: Let us consider an example to  When a method is understand the terminology:- called

Volume-2 | Issue-3 | March,2015 | Paper-13 90 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

 When an Example point cut designators II exception is thrown  When the target object is of type  When a variable is SomeType accessed  target(SomeType)  When the executing code belongs  Point cut definitions consist of a to class MyClass left-hand side and a right-hand  within(MyClass) side, separated by a colon  When the join point is in the  The left-hand side control flow of a call to a Test's consists of the point cut no-argument main method name and the point cut  cflow(call(void parameters (i.e. the data Test.main())) available when the events happen) Point cut designator wildcards  The right-hand side  It is possible to use wildcards to consists of the point cut declare point cuts: itself  execution (* *(..)) Example point cut:  Chooses the point cut setter(): call(void setX(int)); execution of any  The name of this point method regardless cut is setter of return or  The point cut has no parameter types parameters  The point cut itself is  call(* set(..)) call(void setX(int))  Chooses the call  The point cut refers to to any method any time the void named set setX(int) method is called regardless of return or Example point cut designators I parameter type  When a particular method body  In case of executes: overloading there  execution(void may be more than Point.setX(int)) one such set  When a method is called: method; this  call(void Point.setX(int)) pointcut picks out  When an exception handler calls to all of them executes:  handler(ArrayOutOfBoun Point cut designators based on types dsException)  You can select elements based on  When the object currently types. For example, executing (i.e. this) is of type  execution(int *()) Some Type:  Chooses the  this(SomeType) execution of any method with no

Volume-2 | Issue-3 | March,2015 | Paper-13 91 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

parameters that made from the returns an int code in Point’s or  call(* setY(long)) Line’s type  Chooses the call declaration to any setY  within(*) && method that takes execution(*.new(int)) a long as an  Chooses the argument, execution of any regardless of constructor taking return type or exactly one int declaring type argument,  call(* Point.setY(int)) regardless of  Chooses the call where the call is to any of Point’s made from setY methods that  !this (Point) && call (int take an int as an *(...)) argument,  Chooses any regardless of method call to an return type int method when  call(*.new(int, int)) the executing  Chooses the call object is any type to any classes’ except Point constructor, so long as it takes Pointcut designators based on exactly two ints as modifiers arguments  call (public * *(..))  Chooses any call to a Point cut designator composition public method  Point cuts compose through the  execution (!static * *(..)) operations or (“||”), and (“&&”)  Chooses any execution of and not (“!”) a non-static method  Examples:  execution (public !static * *(..))  target(Point) && call(int  Chooses any execution of *()) a public, non-static  Chooses any call method to an int method  Point cut designators can be with no arguments based on interfaces as well as on on an instance of classes Point, regardless of its name Kinds of advice  call (* *(..)) &&  AspectJ has several kinds of (within(Line) || advice; here are some of them: within(Point))  Before advice runs as a  Chooses any call join point is reached, to any method before the program where the call is

Volume-2 | Issue-3 | March,2015 | Paper-13 92 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

proceeds with the join – can continue original point execution, bypass  After advice on a execution or cause particular join point runs execution with an altered after the program context proceeds with that join – can cause execution of point the join point multiple  after returning times advice is executed after a method returns normally Introduction  after throwing  An introduction is a member of advice is executed an aspect, but it defines or after a method modifies a member of another returns by type (class). With introduction throwing an we can exception  add methods to an  after advice is existing class executed after a  add fields to an existing method returns, class regardless of  extend an existing class whether it returns with another normally or by  implement an interface in throwing an an existing class exception  convert checked  Around advice on a join exceptions into point runs as the join unchecked exceptions point is reached, and has explicit control over AspectJ: - whether the program  Aspectj is: proceeds with the join a general-purpose Ao point extension to Java • Advice is a method like construct Java platform compatible that expresses the action to be easy to learn and use taken at the join points that are freely available under an captured by a pointcut. Open Source license • Before advice  Aspectj enables the modular – executes prior to the join implementation of a wide range point of crosscutting concerns • After advice  When written as an aspect the – executes following the structure of a crosscutting join point concern is explicit and easy to • Around advice reason about – surrounds the join point’s  Aspects are modular execution  AspectJ enables:

Volume-2 | Issue-3 | March,2015 | Paper-13 93 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

Name-based crosscutting (tend to affect a small number of What about encapsulation? other classes) • AOP breaks encapsulation in a Property-based controlled manner. crosscutting (range from • Encapsulation is broken between small to large scale) classes and aspects.  Adoption of it into an existing • Aspects marked as privileged project can be a straightforward have access to the private and incremental task: members of a class. . to begin with development • Encapsulation is preserved aspects between classes. . other paths are possible, • An aspect encapsulates a depending on the needs of the crosscutting concern. projects AspectJ – Aspects  The goals of the AspectJ project • Aspects can: are to make AOP technology – Include data members available to a wide range of and methods. programmers, to build and – Be declared abstract support an AspectJ user (won’t be weaved). community – Have access specifiers. – Extend classes or aspects. AspectJ – Join point model – Implement interfaces. • Any identifiable execution point: • Aspects are not the same as - method – catch classes: body block – Cannot be directly – method – class instantiated. call (static) – Cannot inherit from – constru initializ concrete aspects. ctor ation – Can be marked as body – object privileged. – constru initializ Static crosscutting ctor call ation • Dynamic crosscutting modifies – field – object the execution behavior of the access pre- program. initializ • Static crosscutting modifies the ation structure of the program. – advice – Member introduction. executi – Type-hierarchy on modification. – Compile-time warning declaration. – Exception softening. • All join points have a context. • Member introduction adds data Certain point cuts can capture the members and methods to classes context and pass it to the advice.

Volume-2 | Issue-3 | March,2015 | Paper-13 94 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

Modifying the class hierarchy • Aspect based policy enforcement is reusable. • Existing classes can be declared • AOP can be used for “Design by to implement an interface or Contract”. extend a super class. • Works as long as Java Policy Enforcement in AspectJ inheritance rules are not violated • and runtime (no multiple inheritances). enforcement. declare parents : [Type] • In AspectJ it is possible to implements [Interface List]; specify custom compile time declare parents : [Type] warnings and errors using extends [Class]; pointcuts. • Aspects can be made dependant only on a base type or interface. declare warning : get(* System.out) This makes aspects more || get(* System.err) reusable. : “consider using Logger.log() instead”; AspectJ – Exception softening declare error : set(public * *) || • Converts a checked exception get(public * *) into a runtime exception. : “nonpublic access is not allowed”; • Sometimes it can be inconvenient • Runtime enforcement can be to have to deal with checked achieved through advice that exceptions. Involves a detects policy violations. proliferation of try/catch blocks and throws clauses. Example: Aspect precedence SQLException in JDBC API • It is possible for more than one declare soft : SQLException : piece of advice to apply to a join within(DatabaseAccess); point. • Exception is automatically • It may be important to control the rethrown as a order in which advice is applied. org..lang.SoftException declare precedence : Aspect1, Aspect2, ... ; Policy Enforcement • In the absence of any specified • Mechanism for ensuring that precedence control, the order in system components follow which the advice is applied is certain programming practices. non-deterministic (at compile • For example; enforce that public time). access to instance variables is • If more than one piece of advice prohibited. in the same aspect applies to a • Avoid incorrect usages of an point cut, then the advice that API. comes first in the file has • Ensures better quality. precedence. • In AOP policy enforcement concerns can be implemented in Aspect association aspects.

Volume-2 | Issue-3 | March,2015 | Paper-13 95 Journal of Advance Research in Computer Science & Engineering ISSN: 2456-3552

• Typically an aspect represents a • Like all new technologies, AOP singleton object (aspect instance) may--or may not--catch on in a that is instantiated by the system. big way. • It may be useful to have more than one instance of an aspect in References :- the system. Can create associations between aspect 1. dictionary.reference.com/browse/a instances and other objects. spect-oriented+programming • Can associate a new aspect 2. ftp://ftp.inf.ufrgs.br/pub/pod/artigos instance with a target object by /article.ps.gz using a point cut. 3. sit.iitkgp.ernet.in/research/aut05vo l/topic12.ppt 4. www.ijetae.com/files/Volume2Issu Conclusion e4/IJETAE_0412_81.pdf • AOP has many potential benefits. • Higher modularization. • Cleaner responsibilities for individual modules. • Improved separation of concerns. • Easier system evolution. Much easier to add crosscutting functionality. • More code reuse. • Can make code easier or harder to understand. • Already starting to become mainstream (JBoss, JDO, Spring). • Like any new technology, AOP can be abused. • Aspect-oriented programming (AOP) is a new paradigm--a new way to think about programming • AOP is somewhat similar to event handling, where the “events” are defined outside the code itself • AspectJ is not itself a complete , but an adjunct to Java • AspectJ does not add new capabilities to what Java can do, but adds new ways of modularizing the code • AspectJ is free, open source software

Volume-2 | Issue-3 | March,2015 | Paper-13 96