698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into...

20
Tool-Supported Refactoring of Existing Object-Oriented Code into Aspects David Binkley, Member, IEEE, Mariano Ceccato, Student Member, IEEE, Mark Harman, Filippo Ricca, and Paolo Tonella, Member, IEEE Abstract—Aspect-Oriented Programming (AOP) provides mechanisms for the separation of crosscutting concerns—functionalities scattered through the system and tangled with the base code. Existing systems are a natural testbed for the AOP approach since they often contain several crosscutting concerns which could not be modularized using traditional programming constructs. This paper presents an automated approach to the problem of migrating systems developed according to the Object-Oriented Programming (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined to transform OOP to AOP and has been implemented in the AOP-Migrator tool, an Eclipse plug-in. A set of enabling transformations from OOP to OOP complement the initial set of refactorings. The paper presents the results of four case studies, which use the approach to migrate selected crosscutting concerns from medium-sized Java programs (in the range of 10K to 40K lines of code) into equivalent programs in AspectJ. The case study results show the feasibility of the migration and indicate the importance of the enabling transformations as a preprocessing step. Index Terms—Aspect-oriented software development, refactoring, program transformation. Ç 1 INTRODUCTION A SPECT-ORIENTED Software Development (AOSD) is a programming paradigm in which “crosscutting con- cerns” that pervade a system are isolated and extracted into separate modules called aspects. Unlike traditional mod- ules, which must be referenced explicitly by the program (e.g., via procedure calls), aspects add functionalities to the base code by intercepting the execution flow, without any need for the base code to mention the aspect code explicitly. In other words, the base code remains oblivious to the functionality added by an aspect, and it is the aspect that specifies (quantifies) the places in the base program affected by the new functionality [10]. Examples of crosscutting functionalities that benefit from the obliviousness and quantification mechanisms offered by AOSD include persistence, logging, caching, transaction management, and contract enforcement. The motivation which underpins the AOSD paradigm is that these crosscutting functionalities are scattered through- out the program and tangled with the base functionalities, with a corresponding detrimental effect upon many soft- ware engineering activities, such as program comprehen- sion, maintenance, and evolution. In the AOSD paradigm, the base code that implements the core functionality of the system is disentangled from and oblivious to the cross- cutting aspect code, thanks to the quantification constructs available in aspects. It is expected that this form of disentanglement of base code from aspect code will allow the two to be understood, developed, tested, and main- tained independently from one other, with the base code free of references to any other crosscutting concern. In order to extend the benefits of AOSD to existing systems, a significant reverse and reengineering effort will be required. Moreover, the execution of reverse and reengineering studies is expected to contribute to the clarification of the applicability of AOSD to real systems, as well as to the refinement of the AOP constructs and concepts themselves. This reverse and reengineering effort will need to identify and extract from existing programs the code which denotes the crosscutting functionality and to refactor these existing programs within an aspect-oriented reformulation of the original program. In the rest of this paper, we use the term “migration” to indicate the whole process used to move an object-oriented application to be aspect-oriented, so as to exploit the novel constructs and code-structuring opportunities offered by the aspects. “Refactoring” indicates a specific activity within migration, which consists of small, controlled, and largely automated program transformations, resulting in a step forward in the migration process. Refactoring consists of semantic preserving code transformations that improve internal code organization. As with other migrations and conversions [6], [22], [34], [36], the refactorings involved in migrating from OOP to AOP must be automated to avoid unsustainable cost. Previous authors have identified two important phases in the migration from OOP to AOP: aspect mining [3], [25], [30], [33] and aspect extraction (including object-to-aspect refactoring) [15], [27], [35]. In aspect mining, the problem is to identify code which is likely to implement a crosscutting concern. This is a semiautomated process, in which a tool identifies candidate aspects for human consideration. As with related tool-assisted code analysis techniques, there is a trade-off between locating all viable candidates and identifying as few false positives as possible. 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006 . D. Binkley is with Loyola College in Maryland, 4501 North Charles Street, Baltimore, MD 21210-2699. E-mail: [email protected]. . M. Ceccato, F. Ricca, and P. Tonella are with ITC-irst, Via Sommarive 18, 38050 Povo (Trento), Italy. E-mail: {ceccato, ricca, tonella}@itc.it. . M. Harman is with King’s College London, Strand, London, WC2R 2LS, UK. E-mail: [email protected]. Manuscript received 19 Dec. 2005; revised 4 Apr. 2006; accepted 20 July 2006; published online 27 Sept. 2006. Recommended for acceptance by T. Gyimothy and V. Rajlich. For information on obtaining reprints of this article, please send e-mail to: [email protected], and reference IEEECS Log Number TSE-0335-1205. 0098-5589/06/$20.00 ß 2006 IEEE Published by the IEEE Computer Society

Transcript of 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into...

Page 1: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

Tool-Supported Refactoring of ExistingObject-Oriented Code into AspectsDavid Binkley, Member, IEEE, Mariano Ceccato, Student Member, IEEE,

Mark Harman, Filippo Ricca, and Paolo Tonella, Member, IEEE

Abstract—Aspect-Oriented Programming (AOP) provides mechanisms for the separation of crosscutting concerns—functionalities

scattered through the system and tangled with the base code. Existing systems are a natural testbed for the AOP approach since they

often contain several crosscutting concerns which could not be modularized using traditional programming constructs. This paper

presents an automated approach to the problem of migrating systems developed according to the Object-Oriented Programming

(OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined to transform OOP to

AOP and has been implemented in the AOP-Migrator tool, an Eclipse plug-in. A set of enabling transformations from OOP to OOP

complement the initial set of refactorings. The paper presents the results of four case studies, which use the approach to migrate

selected crosscutting concerns from medium-sized Java programs (in the range of 10K to 40K lines of code) into equivalent programs

in AspectJ. The case study results show the feasibility of the migration and indicate the importance of the enabling transformations as a

preprocessing step.

Index Terms—Aspect-oriented software development, refactoring, program transformation.

Ç

1 INTRODUCTION

ASPECT-ORIENTED Software Development (AOSD) is aprogramming paradigm in which “crosscutting con-

cerns” that pervade a system are isolated and extracted intoseparate modules called aspects. Unlike traditional mod-ules, which must be referenced explicitly by the program(e.g., via procedure calls), aspects add functionalities to thebase code by intercepting the execution flow, without anyneed for the base code to mention the aspect code explicitly.In other words, the base code remains oblivious to thefunctionality added by an aspect, and it is the aspect thatspecifies (quantifies) the places in the base program affectedby the new functionality [10]. Examples of crosscuttingfunctionalities that benefit from the obliviousness andquantification mechanisms offered by AOSD includepersistence, logging, caching, transaction management,and contract enforcement.

The motivation which underpins the AOSD paradigm isthat these crosscutting functionalities are scattered through-out the program and tangled with the base functionalities,with a corresponding detrimental effect upon many soft-ware engineering activities, such as program comprehen-sion, maintenance, and evolution. In the AOSD paradigm,the base code that implements the core functionality of thesystem is disentangled from and oblivious to the cross-cutting aspect code, thanks to the quantification constructsavailable in aspects. It is expected that this form ofdisentanglement of base code from aspect code will allow

the two to be understood, developed, tested, and main-tained independently from one other, with the base codefree of references to any other crosscutting concern.

In order to extend the benefits of AOSD to existingsystems, a significant reverse and reengineering effort willbe required. Moreover, the execution of reverse andreengineering studies is expected to contribute to theclarification of the applicability of AOSD to real systems,as well as to the refinement of the AOP constructs andconcepts themselves. This reverse and reengineering effortwill need to identify and extract from existing programs thecode which denotes the crosscutting functionality and torefactor these existing programs within an aspect-orientedreformulation of the original program.

In the rest of this paper, we use the term “migration” toindicate the whole process used to move an object-orientedapplication to be aspect-oriented, so as to exploit the novelconstructs and code-structuring opportunities offered bythe aspects. “Refactoring” indicates a specific activitywithin migration, which consists of small, controlled, andlargely automated program transformations, resulting in astep forward in the migration process. Refactoring consistsof semantic preserving code transformations that improveinternal code organization. As with other migrations andconversions [6], [22], [34], [36], the refactorings involved inmigrating from OOP to AOP must be automated to avoidunsustainable cost.

Previous authors have identified two important phasesin the migration from OOP to AOP: aspect mining [3], [25],[30], [33] and aspect extraction (including object-to-aspectrefactoring) [15], [27], [35]. In aspect mining, the problem isto identify code which is likely to implement a crosscuttingconcern. This is a semiautomated process, in which a toolidentifies candidate aspects for human consideration. Aswith related tool-assisted code analysis techniques, there isa trade-off between locating all viable candidates andidentifying as few false positives as possible.

698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

. D. Binkley is with Loyola College in Maryland, 4501 North Charles Street,Baltimore, MD 21210-2699. E-mail: [email protected].

. M. Ceccato, F. Ricca, and P. Tonella are with ITC-irst, Via Sommarive 18,38050 Povo (Trento), Italy. E-mail: {ceccato, ricca, tonella}@itc.it.

. M. Harman is with King’s College London, Strand, London, WC2R 2LS,UK. E-mail: [email protected].

Manuscript received 19 Dec. 2005; revised 4 Apr. 2006; accepted 20 July2006; published online 27 Sept. 2006.Recommended for acceptance by T. Gyimothy and V. Rajlich.For information on obtaining reprints of this article, please send e-mail to:[email protected], and reference IEEECS Log Number TSE-0335-1205.

0098-5589/06/$20.00 � 2006 IEEE Published by the IEEE Computer Society

Page 2: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

The problem of identifying candidates for aspects incode has been well studied in the literature, as discussed inthe Related Work section. However, the problem ofextracting the aspects from an OO program in order torefactor it into an equivalent AOP program is much lesswell-studied in the literature. It is this problem which formsthe focus for the work reported in this paper. This paperconsiders the problem of determining sensible pointcuts tointercept the execution and redirect it to the aspect code,together with the refactoring transformations which pack-age the aspectual functionality in the AOP version of theprogram.

Such a process must be guaranteed to preserve theoriginal behavior while modularizing the code of thecrosscutting functionality. This requires that the code beingrefactored satisfies certain preconditions. In order to meetthem, the OO code is transformed by a sequence of“enabling transformations” which map OO code toOO code, rendering it into a suitable form to enable therefactoring transformations.

In common with other refactoring and code migrationwork [36], human guidance is both necessary and desirable;the process requires value judgments regarding trade-offsbest made by a maintenance engineer. The process ofmigrating existing software to AOP is highly knowledge-intensive and any refactoring toolkit therefore shouldinclude the user in the change-refine loop. However,notwithstanding this inherent and desirable human invol-vement, there is considerable room for automation.

Key to the aspect extraction is a set of six refactoringtransformations. The paper presents the six refactorings anda tool, AOP-Migrator, which implements them in an Eclipseplug-in. Complementary to these object-to-aspect refactor-ings is the aspect-to-aspect refactoring called “pointcutabstraction,” which aims at improving the quality of theautomatically generated aspect code by unifying computa-tions shared by different advices. Results from the applica-tion of the tool to four medium-sized migration case studiesare then presented. In the case studies, the aspect code isassumed to have been identified by previous approaches.

The case studies show that migration can be achievedusing a relatively small set of refactorings, and they indicatethe need for object-to-object enabling transformations, suchas side effect removal [9], [19] and code-motion transforma-tions [18]. The primary contributions of the paper can besummarized as follows:

1. Six refactorings1 are introduced to support migrationfrom OOP to AOP (some novel, others similar toalternative proposals investigated in parallel byother authors).

2. These refactorings are combined with existingOO transformations in a tool that automates them.2

3. The effectiveness of the approach is explored usingfour medium-scale applications: JHotDraw, Pet-Store, Jaccounting and JSpider. The case studiesprovide evidence that suggests that migration canbe achieved with a simple set of refactoringtransformations. The case studies also point tothe importance of enabling transformations whichtransform an OO program into a semantically

equivalent OO program, in which the refactoringsbecome applicable.

The paper is organized as follows: Section 2 brieflypresents background material on AspectJ to make the paperself-contained. Section 3 describes the six refactorings usedin the migration from OOP to AOP, while Section 4introduces the tool used to implement the approach.Section 5 presents the result of the application of the toolto four medium-sized cases studies. Section 6 describes thework related to that which is presented here, while Section 7concludes with directions for future work. Finally, theAppendix presents a formal program-schematic descriptionof the six refactorings used in this paper.

2 BACKGROUND ON ASPECTJ

Among the programming languages and tools that havebeen developed to support AOSD, AspectJ [21], anextension of Java with aspects, is one of the most popularand best supported. AspectJ offers two main programmingconstructs to modularize crosscutting concerns: pointcutsand introductions. Pointcuts intercept the normal executionflow at specified join points. Aspect code (called advice) canbe executed either before, after, or instead of (around) theintercepted join points. Introductions modify properties ofthe classes they affect by adding methods or fields and bymaking them implement interfaces or specialized super-classes previously unrelated to them. Unlike pointcuts/advices, which alter the dynamic behavior, introductionsoperate statically on the class members and structure (thismay, in turn, have effects on the dynamic behavior in thepresence of dynamic method binding). Aspects can alsomodify the superclass or the implemented interfaces of aclass, via the declare parents construct.

Fig. 1 shows an example aspect that adds persistence to anexisting class, Person. Similar to classes, aspects have fieldsand methods. The aspect PersistentPerson declares twofields,outfile andout, respectively of typeFileOutput-Stream and ObjectOutputStream. Next, the aspectPersistentPerson declares that the interface Serial-

izable is implemented by classPerson. This is achieved bymeans of the AspectJ construct declare parents. More-over, the aspect adds related methods readObject andwriteObject to the current implementation of classPerson. The syntax for the necessary introductions consistsof the base class name, dot-separated by the added method(field) name (e.g., Person.readObject).

In order to serialize all objects of class Person as soon asthey are created, the appropriate join points are all calls toany constructor of class Person. The pointcut person-Creation intercepts such join points. The AspectJ key-word call, followed by a method (constructor) signature,is used to specify a primitive pointcut which intercepts allcalls to the methods (constructors) matching the givensignature. Parameter passing between base code and aspectcode is achieved through context exposure. The AspectJkeyword target is used to expose the object on which theinvocation is performed (in this case, the newly createdPerson object). The exposed context is then availablewithin the advices associated with the pointcut.

The advice to be executed after the pointcut person-Creation is declared by means of the AspectJ keywordafter. Its formal parameters match those exposed in thecorresponding pointcut. The code in the after-advicedefined for the pointcut personCreation stores informa-tion about the Person object being created by calling the

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 699

1. Five of these refactorings were described in the preliminary version ofthis paper which was presented at ICSM 2005 [1].

2. The tool is a complete reimplementation, as an Eclipse plug-in, of theprototype tool presented at ICSM 2005 [1].

Page 3: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

method writeObject on the aspect field out and passingthe Person object to it. In turn, the method writeObject

is known to delegate the write operation to its parameterobject, of type Serializable, by invoking its write-

Object method.Among the other primitive pointcuts provided by the

AspectJ language, execution and handler are relevantfor the present work. ExecutionðhsignatureiÞ interceptsthe execution of any method matching hsignaturei, whilehandlerðhexceptioni) matches any exception handler(catch block) matching hexceptioni. The primitive point-cut withincode is satisfied by join points inside thecode specified after the keyword (e.g., withincode

(Person.new(String))). The primitive pointcut if isused to express a condition to be checked dynamically. Itintercepts all join points making the condition true.Wildcards also can be included in pointcut specifications(e.g., call(* Person.*(..)) indicates a call to anymethod of class Person with any signature).

Advices executed after, before, or instead of a given joinpoint are specified through the keywords after, before,and around, respectively. After-advices can be furtherdistinguished, depending on the kind of “return”: normaltermination is specified as after() returning andexceptional termination as after() throwing. Inside anaround-advice, the original computation can be executedusing proceed(). Around-advices are expected to return avalue of the same type as the intercepted join point.

In addition to target, the primitive constructs providedby AspectJ for context exposure include: args (to exposethe arguments of a method in a call or execution

pointcut) and this (to expose the current object). Bydefault, a single aspect instance is created for each aspectdeclaration. However, it is possible to change the default bymeans of a per-clause option such as pertarget,perthis, percflow, whenever fresh aspect fields arerequired, respectively, each time a new target, this objector control flow matching a given pointcut are encountered.

A useful mechanism provided by AspectJ to supportaspectization of exception handling is the declare softconstruct, which softens an exception so that it needs notbe caught inside the base code and it can be managedcompletely inside an aspect. An example of its usage will be

provided in the following section. More details on thesemantics of AspectJ can be found in the ProgrammingGuide accompanying its distribution (http://aspectj.org) aswell as any of the many books published on the subject(e.g., [21]).

3 ASPECT EXTRACTION

The aspect extraction algorithm has two steps. The first,which does the bulk of the work, uses refactoring to createthe initial pointcut and advice instances necessary toaspectize the OO code selected for migration. The secondstep combines these instances into the final pointcuts andadvices. This section first describes the refactorings andthen describes the merging. The identification of aspectcandidates (aspect mining) and the markup of the coderegions that represent instances of these candidates to berefactored are assumed to have been completed before theextraction begins. These steps can benefit from exploitingaspect mining techniques described in the literature [3], [5],[13], [16], [20], [25], [28], [29], [30], [33]. The regions of codemarked for refactoring fall into one of three cases:

1. whole methods or fields,2. calls to methods, or3. statement sequences (blocks of code).

Extraction of whole methods or fields (Case 1) isstraightforward and requires simply moving the methodor field from a class to an aspect, where it is turned into anAspectJ introduction. Case 3 (statement sequence) can beeasily reduced to Case 2 by applying the well-knownOO transformation Extract Method. For these reasons, thispaper focuses on Case 2. In fact, a sequence of arbitrarystatements to be aspectized can be handled by extractingthem into a separate method, aspectizing the call to such amethod and (if possible and desirable) inlining the methodbody into the advice. In this way, the same mechanicsapplied to calls can be used for arbitrary statements.

Among the high number of refactorings for migrationfrom objects to aspects that have been proposed [2], [8], [15],[17], [27], [35], this work focuses on a small subset, selectedusing a mix of a bottom-up and a top-down approach. Onone hand, a priori knowledge about the constructs provided

700 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

Fig. 1. Example of aspect showing the mechanics of introductions and pointcuts/advices.

Page 4: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

by most aspect languages/frameworks (including AspectJ)and about the kinds of crosscutting concerns that areamenable for implementation through aspects guided us.On the other hand, the execution of case studies steered ourinitial intuitions and led us to refine the catalog. Further-more, this work considers only refactorings whose me-chanics can be fully automated. In fact, one of the aims ofthe present work is to assess the ability of this small list ofrefactorings to cover most of the cases encountered inpractice. The following six refactorings from objects toaspects have been included for evaluation:

. Extract Beginning/End of Method/Handler. Themarked code is at the beginning/end of theenclosing method body or of one of the method’sexception handling blocks.

. Extract before/after Call. The marked code is alwaysbefore or after a method call.

. Extract Conditional. A conditional statement con-trols the execution of the marked code.

. Pre Return. The marked code is just before thereturn statement.

. Extract Wrapper. The marked code is part of awrapper pattern, in which the wrapper code is to beaspectized.

. Extract Exception Handling. The marked code is awhole exception handling block.

Once the code pertaining to a crosscutting concern ismoved from the principal decomposition to an aspectthrough refactoring, proper context exposure mechanismsmust be realized in order to let the advice code access everylocation originally accessed in the base code. The followingcases may occur:

. Access to a method parameter. Parameter exposurecan be achieved by means of the AspectJ args

construct.. Access to a class member. Member access requires

exposure of the implicit parameter this and can beachieved by means of the AspectJ this construct.

. Access to a local variable. Local exposure can beachieved by creating a copy of the local variable inthe aspect (see example below).

When none of the refactorings above apply to a markedcode fragment, OO transformation is resorted to (also calledOO refactorings [11]) in order to make one or more of therefactorings above applicable. Among the possibleOO transformations, the following are regarded as thetwo most important ones in this work: Statement Reorderingand Extract Method. Both can be fully automated (the latteris available in most transformation environments, while theformer requires some nontrivial dependency analysis toensure semantics preservation). Hereafter, transformationsare OO to OO and refactorings are OO to AOP.

Statement Reordering allows the order of two statementsto be exchanged. In its simplest form, this requires that thedefined and referenced variables of the two statements donot overlap. When some overlap does occur betweendefined and referenced variables, it may be possible tomake this transformation applicable by introducing freshlocal variables that store a value that must be preserved.

The second OO transformation, Extract Method, allows asequence of statements to be extracted to a separate method[11]. Method arguments might be required if local variablesor parameters of the original method are referenced in themarked statement block. This transformation makes it

possible to aspectize virtually any marked block of code.However, it impacts the structure of the base code quitedeeply, so it is used as sparingly as possible and as a “lastresort.”

The remainder of this section provides details on the twosteps of the extraction algorithm: First, it describes the sixrefactorings from objects to aspect advice instances. Theirdescription is based on a set of examples, which cover themost common cases and include all three context exposuremechanisms described above. A formal presentation of themechanics associated with each refactoring in the generalcase is given in the Appendix. The second step, whichmerges the advice instances to form the final aspect, is thendescribed.

3.1 Extract Beginning/End of Method/Handler

This refactoring deals with the following case:

The marked code is at the beginning/end of the enclosing methodbody or of one of the method’s exception handling blocks.

Fig. 2 shows the result of applying the refactoring ExtractEnd of Method to a small code fragment. The call to methodg is removed from the body of f. A new aspect, named B, iscreated to intercept the execution of f and insert a call to g

at the end. The target of the call (this) is accessible withinthe aspect advice because of the advice parameter This,which is bound to this by pointcut p. The actualparameter of the call (y) is made accessible (exposed)within the aspect advice because of the advice parameter y,which is bound to the method parameter y by the args

construct used in pointcut p.The variant of this refactoring with the call to be

aspectized at the beginning of the method requires simplychanging the after advice into a before advice. Thevariant with the call in the exception handling blockrequires simply concatenating (through &&) a handler

primitive pointcut at the end of p. When the reapplicationof this refactoring produces a pointcut already generatedbefore (e.g., Extract End of Method applied twice to the samemethod), the pointcut and the associated advice are notduplicated. The marked code is inserted at the beginning/end (respectively, for Extract End/Beginning) of the pre-viously generated advice body. If a method has multipleexit points, the same marked code fragment must appearbefore each of them in order for this refactoring to beapplicable.

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 701

Fig. 2. Example of refactoring: Extract End of Method.

Page 5: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

3.2 Extract before/after Call

This refactoring deals with the following case:

The marked code is always before or after another call.

Fig. 3 shows an application of the refactoring Extract afterCall. In the aspect B, the pointcut p1 intercepts the call to h

that occurs within the execution of method f. After-advicereintroduces the call to g after each call to h.

Pointcut p2, the related advice, and the percflow

clause are not necessarily part of this refactoring. They needto be included only if a local variable of the interceptedmethod has to be exposed in the aspect (which can occur inany of the six refactorings presented herein). Often,successive refactorings make the context exposing pointcut(p2) unnecessary, since the local variable becomes com-pletely confined within the aspect code. In such cases, theaspect can be simplified and the context exposure code canbe removed altogether.

Since the call to g includes the local variable d as aparameter, a copy of the local variable is created inside theaspect. This is achieved by intercepting every assignment tothe local variable (pointcut p2) and copying the value intothe aspect variable before returning it (around-adviceassociated with p2). In order to create a fresh new copy ofthe variable in the aspect each time the control flow reachesthe execution of the method containing the local variable,the aspect must be instantiated for each control flow(percflow clause) in which the method is executed.

In cases when the local variable is no longer used inthe base code, it can be turned into an aspect variable.This happens typically when the local variable is itselfpart of the concern being aspectized. With reference to theexample in Fig. 3, let us consider what happens if the firststatement of f is also to be aspectized. Moving it to theaspect B is a straightforward application of the refactoring

Extract Beginning of Method described before, because thereturned value is no longer used in the base code. Oncethis second refactoring has been applied, the set of joinpoints intercepted by pointcut p2 becomes empty (this iseasily checked by the AspectJ compiler). Correspondingly,there is no need for the code fragments within dashedboxes in Fig. 3, which can be removed from the aspect.The resulting aspect code is much clearer and closer to thecode that would be written manually. Thus, although thecontext exposure associated with local variables might becomplex, it is an acceptable intermediate step if the localvariable is part of the concern and is completely moved tothe target aspect by successive refactorings.

In the presence of multiple calls to the intercepted

method (e.g., h in Fig. 3) the refactoring Extract before/after

Call is applicable only if each call is preceded/followed by

the call to be aspectized (g in Fig. 3). If this is not the case,

the refactoring is not applicable and the use of some

enabling transformation (such as Extract Method) should be

considered.

3.3 Extract Conditional

This refactoring deals with the following case:

A conditional statement controls the execution of the marked code.

Fig. 4 shows an example of this refactoring. Theconditional statement if (b) is considered to be part ofthe aspect, in that it determines the execution of the callbeing aspectized (in Fig. 4, the call to g). Thus, it becomes adynamically checked condition incorporated into theaspect’s pointcut (using the AspectJ syntax if (This.b)).For the execution to be intercepted by pointcut p, thecondition This.b must be true; in which case, the newbody of method f is replaced by the call to g, as specified inthe around-advice.

Two variants of Extract Conditional are worth mention-ing. First, if the “x++;” were not under the control ofcondition b (placing it at the top-level in f), it would besufficient to add a proceed statement at the end of thearound-advice to ensure that it is always executed (bothwhen the advice is triggered and when the execution flowsnormally). Second, if method g is in the else part of theconditional statement, it is sufficient to use if (!This.b)

instead of if (This.b) in the pointcut.

702 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

Fig. 3. Example of refactoring: Extract After Call.

Fig. 4. Example of refactoring: Extract Conditional.

Page 6: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

3.4 Pre Return

This refactoring deals with the following case:

The marked code is just before the return statement.

Fig. 5 shows an example of Pre Return. The call to g ismoved from the method body to the around-advice. Theadvice code contains a proceed invocation, which triggersthe execution of the intercepted method f. Its return valueis stored into a temporary variable (y) and returned afterthe invocation of the aspectized statement (i.e., the call tomethod g), which changes its value.

This refactoring is a variant of Extract End of Methodthat occurs whenever the code to be aspectized is at theend of a value-returning method. The main difference isthe usage of an around-advice, instead of an after-advice,which is required whenever the returned value is affectedby the aspectized statement. Preservation of the semanticscan be achieved by 1) executing the original method (viaproceed), 2) executing the aspectized call (in the advice),and 3) returning the final value. An after-advice wouldswap the execution order of 2 and 3.

3.5 Extract Wrapper

This refactoring deals with the following case:

The marked code is part of a wrapper pattern, in which the wrappercode is to be aspectized.

Fig. 6 shows an example of Extract Wrapper. The object xis wrapped into y before being used as the actual parameterof a call to g (see also Gamma et al.’s pattern [12]). In orderto move the creation of the wrapper object (underlinedstatement in method f) to the aspect, the unwrappedobject x is used in the refactored code for the method f asthe actual parameter of the call to method g. Such a call isintercepted by the pointcut p, which exposes its argument.The associated around-advice uses this argument, which isknown to belong to class X, to create the wrapper object y.This object is passed to method g by restoring the originalmethod invocation (proceed construct) with a newargument.

Similar to Call before Method, Extract Wrapper is applicableonly if the body of f contains just one call to g, or multiplecalls all of which participate in the same wrapper pattern. Ifthis is not the case, application of this refactoring in analternative form can be considered. The pointcut p mayintercept the creation of the object x, instead of the call to g,

by means of the “call (X.new())” pointcut designator.By exposing the target of the call to the constructor (targetconstruct in AspectJ), the unwrapped object x can be madeavailable within the around-advice, which will containexactly the same code as the around-advice shown in Fig. 6.

3.6 Extract Exception Handling

This refactoring deals with the following case:

The marked code is a whole exception handling block.

As an example, consider the refactoring of theexception handling code marked in Fig. 7, so as to moveit to an aspect. The remaining code should becomeoblivious to any exception of type E raised in the body ofmethod A.f. This is achieved by means of the AspectJconstruct declare soft, used to soften all exceptions oftype E raised within the code of A.f (see Fig. 7). Thenewly created aspect B can intercept the exceptions oftype SoftException raised during the execution of A.f.Since these are produced by the softening of exception E

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 703

Fig. 5. Example of refactoring: Pre Return.

Fig. 6. Example of refactoring: Extract Wrapper.

Fig. 7. Example of refactoring: Extract Exception Handling.

Page 7: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

in aspect B, it is possible to obtain the original exception(through invocation of getWrappedThrowable) and torestore the original exception handling computation, bymeans of an after-advice. This refactoring was suggestedby Laddad [23].

3.7 Pointcut Abstraction

The above refactorings extract each instance (code frag-ment) of an aspect marked in the code. The final step,pointcut abstraction, merges the separate instances into asingle advice whenever possible.

The merge is primarily a syntactic combination of thepointcuts and advices for the extracted aspect instances.When the advice bodies are exactly the same, the combina-tion requires just determining the union of the pointcutsproduced by refactoring. For example, a pointcut clausemay describe the call to a particular method beingintercepted. The remaining clauses describe the context inwhich the advice is to be woven. A disjunction of theseclauses is formed and added to the pointcut specifyingthe call.

The merge of the advice instances is often trivial. As seenbelow, the predominant case is for the instances of a givenaspect to have the same advice. Minor differences can beaccommodated by the inclusion of conditionals. The oneexception to this is when the exposed context involvesdifferent types. For example, if some logging code wascalled from method m1 of class C1 and from method m2 ofclass C2, then the pointcut instances would be

. before(C1 This) : log_pointcut (This) � � �

. before(C2 This) : log_pointcut (This) � � �Here, it is necessary to replace C1 and C2 with a uniquetype, used for the parameter This. In this case, standardpractice is to create a new interface for the advice and use itin place of C1 and C2. The aspect declares that C1 and C2implement such an interface.

4 AOP-MIGRATOR

The refactorings presented in the previous section havebeen implemented in a prototype tool called AOP-Migrator(http://se.itc.it/aop-migrator). The tool supports an itera-tive refactoring process, which has been derived fromprevious work [1]. In this section, the process and the toolare described.

4.1 Iterative Refactoring Process

The migration process makes the assumption that aspectmining has already been performed on the system. Theresult of mining is a marked source code, where all the codefragments that have been identified as part of a crosscuttingconcern are surrounded by block comments containingspecial annotations.

Fig. 8 shows an overview of the migration process. Theprocess consists of a loop over all the marked portions ofcode. In turn, each marked segment of code is analyzed inisolation and, with the involvement of the user, moved to anaspect. The iteration goes on until no more markedstatements remain in the base code.

A process iteration consists of several steps, the first ofwhich is Discovery. During this step, the tool analyzes thecurrent marked code and compares it with the refactoringpatterns. A match occurs when the corresponding refactor-ing is applicable to the current code fragment, so it can beused to transform it. The output of Discovery is the list of

applicable refactorings. Items in the list are ranked top-down, with the best refactoring at the top. A relative scale ofpriorities among the refactorings was defined, based on theimpact that each refactoring has on the original code andthe complexity and generality of the aspect code that isgenerated. For example, Extract after Call and Extract beforeCall are given low priority, because the future insertion ofanother identical call, during the evolution of the software,might invalidate the refactoring precondition (all inter-cepted calls must be preceded/followed by the samemarked code fragment). In other words, the pointcutgenerated by this refactoring is considered quite fragilewith respect to future possible code changes.

In the second process step, Selection, the user chooseswhich refactoring to apply among the applicable ones,either following or ignoring the assigned priority. The toolallows the user to evaluate the alternatives by looking at apreview of the resulting source code for each refactoringbefore actually applying it. The user can also decide to leavethe current portion of code unchanged and go on with thenext portion, deferring the transformation to a futureiteration. Of course, this is mandatory when no refactoringpattern matches the current portion of code.

In the Transformation step, enabling transformations areused to change the current code fragment in such a way thatit matches a previously unmatched refactoring pattern, thusmaking the corresponding refactoring applicable. Theseenabling transformations can be well-known object-oriented transformations, such as Extract Method or State-ment Reordering, or ad hoc (manual) transformations.

If one of the proposed refactorings is consideredappropriate, the user simply selects it for the next processstep, Refactoring. In this step, the marked code is removedfrom the class and is moved to an aspect advice. A properpointcut is generated to intercept the join point in themodified base code, according to the mechanics of theselected refactoring (as detailed in the Appendix). As apostprocessing, the aspect-to-aspect refactoring for pointcutabstraction may be also applied to the resulting code.

4.2 AOP-Migrator GUI

The interaction with the user starts with the dialog shownin Fig. 9a. The user is required to specify the target aspect(where the concern code is placed). The default is the aspectselected in the previous iteration.

704 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

Fig. 8. Refactoring process overview.

Page 8: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

After that, the wizard proposes the list of applicablerefactorings ordered by priority (see Fig. 9b). The Norefactoring item is always present. When the user selects arefactoring, the wizard shows the preview dialog (Fig. 9c).In the preview dialog, the upper panel lists all the sourcefiles that are involved in the change. If a file is selected inthe upper panel, the related detailed change is shown in thelower panel, where the source code before and after therefactoring is displayed. Up to this point, the refactoring hasnot yet been applied and the data in the previous dialogscan still be modified by navigating with the Back and Nextbuttons. The change is actually committed when the userpresses Finish.

Some enabling OO transformations are already availablein the Eclipse framework as defined in the JDT plug-in (e.g.,Extract Method and Promote Local Variable to Field). Othertransformations, not yet implemented, are performedmanually.

In its current version, AOP-Migrator checks the applic-ability conditions of the refactorings only at the syntacticlevel. Further human judgment may be necessary inspecific cases (e.g., exposure of local variables). Pointcutabstraction is not yet included in AOP-Migrator. As withOO refactoring [11], it is highly advisable that each smallcode transformation step be followed by regressiontesting, via automated execution of unit tests. Although

not ensuring semantics preservation, regression testingincreases the confidence in the correctness of the trans-formation.

5 EXPERIMENTAL RESULTS

This section describes the results obtained by applyingAOP-Migrator to four case studies. Their source code wasobtained from the public domain. The migration taskexecuted on them was designed to simulate a typicalscenario of smooth migration toward AOSD. This consistsof small incremental steps and is initially focused on asingle, well-known, and clearly recognizable concern to bemigrated. The aim is not to restructure the applicationcompletely according to the AOSD paradigm. Rather, acontrolled and well-identified modification is made, inorder to assess its execution and the related opportunitiesfor automation. The refactored code for the four case studiesis available at http://se.itc.it/aop-migrator.

5.1 Case Studies

Table 1 shows some descriptive statistics for the fourprograms considered. The range of their applicationdomain is quite wide. JHotDraw is an OO framework forthe development of applications supporting the interactive

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 705

Fig. 9. (a) Aspect selection dialog. (b) Refactoring selection dialog. (c) Preview of the resulting source code.

Page 9: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

creation and manipulation of graphical objects. PetStore is aJ2EE e-business application supporting order, sale, andshipment of products purchased on the Web. JSpider is aWeb robot able to download a target Web site and to checksome internal server and link errors. JAccounting is a Web-based business accounting system, which includes supportfor invoice and account management, as well as Web access.The size of these applications is typical of medium(nontrivial) Java systems. The number of lines of code(LoC) was measured on all source files for the applicationclasses, test classes excluded. It includes comments andblank lines.

A single crosscutting concern was manually identifiedfor migration in each application. Based on the availabledocumentation as well as code reading, the authorsdetermined the concern that looked the best (most obviousand natural) candidate for aspectization. The concern codewas annotated manually, without any aspect miningsupport. For JHotDraw and for PetStore, the refactoredconcern (respectively, Undo and Contract enforcement) hasbeen used as a candidate aspect in other studies [25], [7]. ForJSpider and JAccounting, the selected concern is one of thetypical examples of aspects reported in the introductoryliterature on AOSD (respectively, Logging and Transactionmanagement).

JHotDraw/Undo. In JHotDraw the execution of com-mands for the manipulation of graphical objects relies upona hierarchy of classes which descend from AbstractCom-mand. Each class in the hierarchy implements (or inherits)methods to set/get the undo activity, i.e., to store or retrievethe information necessary to undo the command. Eachdrawing tool available in JHotDraw is responsible forsetting/getting the undo activity upon command execution,

the related code being highly scattered and tangled with thebase code.

PetStore/Contract enforcement. PetStore uses XML asthe standard representation format for its data. DuringXML parsing, the actions associated with the normalexecution flow are mixed with checks on the occurrenceof errors. If the document does not respect the prescribedformat (both the syntactic constraints and the semanticcontracts), an exception is raised, which requires corre-sponding exception management code. The contract en-forcement and exception handling code is highly scattered,replicated, and tangled with the base code.

JSpider/Logging. JSpider keeps track of the activities itperforms and of the problems encountered into a log file.The statements to write logging information are highlyscattered, since they occur wherever an activity takes placesand an error can happen. The code fragments thatimplement logging are often replicated and they have littleto do with the core functionalities of this application.

JAccounting/Transaction management. Transactionmanagement is implemented in JAccounting using a basicidiom, which is replicated and slightly modified at severalplaces in the program. The idiom consists of the followingsteps:

1. A session is started.2. One or more operations are executed.3. The operations are committed.4. If an error occurred during Step 1, 2, or 3, and an

exception was raised, operations are undonethrough rollback.

5. In case of both normal and exceptional termination,the session is closed.

This idiom is mixed with the core logic, which iscorrespondingly quite obscured.

5.2 Refactoring

Table 2 shows some statistics on the OO transformationsthat have been used to enable the application of the sixproposed object-to-aspect refactorings. Overall, they re-present a remarkable proportion of the total refactoringeffort (40 percent of the total refactorings are enablingOO transformations). Among them, around one-third of thecases are either Statement Reordering or Extract Method. Thus,the experimental results confirm our intuition that these

706 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

TABLE 1Java Programs to Be Refactored and Refactored Aspect

TABLE 2Enabling OO Transformations Applied to the Four Case Studies

Page 10: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

two refactorings play a major role in the migration of realcode. The remaining cases are almost equally split betweenad hoc transformations that depend on the specificorganization of the code and must be carried out manually,and other OO transformations that are either alreadyavailable in Eclipse as OO transformations (e.g., ExtractLocal Variable, Promote Local Variable to Class Field) or thatcould be easily implemented and added to the existing ones(e.g., Push Assignment). It is interesting to note that, in total,two-thirds of the enabling OO transformations are auto-mated (or automatable). This means that although theenabling OO transformations represent an important cost inthe migration process, there is space to support theirexecution through automated transformations.

Among the enabling refactorings, Extract Method is theone that may be potentially detrimental to the code quality.In practice, what we observed in our four case studies isthat the extracted methods typically represent meaningful,functionally cohesive, abstractions. Often, they belong tolong methods (hence the difficulty of finding unique joinpoints) that can be better organized into smaller units.

Table 3 shows the distribution of the six proposedrefactorings from objects to aspects, when applied to thefour case studies. Three of them appear to play a major role:Extract Begin/End, Extract before/after Call and ExtractException. Among the remaining three refactorings, ExtractConditional and Extract Wrapper gave some contribution tomigration, accounting in total for around 12 percent of therefactoring instances. Pre Return is the least usedrefactoring.

The wrappers refactored in JHotDraw typically serve thepurpose of adding the undo functionality to a command.For example, when the “Edit” menu is created, the menuitems added to it are commands (e.g., PasteCommand).Instead of adding such commands directly, an instance ofUndoableCommand is added, which wraps the actualcommand. Both PasteCommand and UndoableCommand

implement the interface Command.In JAccounting, the typical transaction management

idiom (see description above) involves intercepting thebeginning/end of methods to initiate/terminate a session.Moreover, exception handling associated with transactionfailures are moved to the aspect. Hence, the high number ofBegin/end and Exception reported in Table 3.

The high number of refactorings of type Conditionalapplied to PetStore is due to the way contract enforcement

was implemented. During the traversal of XML trees,constraints are checked in a conditional statement, wherenodes and attributes are retrieved and verified for sanity. Ifthe check fails, an exception is raised to signal the error.After refactoring, such checks are completely performedwithin an aspect.

Overall, the data in Tables 2 and 3 suggest that, inpractical cases, a limited number of automated refactoringsfrom objects to aspects is sufficient to migrate an existingapplication. At the same time, they indicate that theapplication cannot be migrated without transformation. Inorder to untangle the base code from the concern to beaspectized and in order to let the aspect intercept properjoin points in the base code, some enabling OO transforma-tions are necessary. However, the majority of them can beautomated and added (when not already available) to thelist of those supported by existing tools (such as Eclipse).

5.3 Pointcut Abstraction

The second step of the extraction is the merge of theindividual advice instances into the final aspect. In general,pointcut abstraction is a research area in itself, whichdeserves further study and investigation [14], [32]. How-ever, given the structure of the pointcut instances extractedby AOP-Migrator, the simple syntactic merge strategydescribed in Section 3 is often sufficient. In order to makea preliminary assessment of its potential to improve theoutput of the refactoring, we consider merging the aspectinstances extracted from JAccounting.

The JAccounting code contains 45 instances (i.e., distinctcode fragments) of the transaction aspect that capturecreating a new transaction, committing a transaction, andaborting a transaction. After pointcut abstraction, these areintercepted using four pointcuts, as aborting a transactionsometimes generates a stack dump.

Fig. 10 illustrates the result of merging the 15 createtransaction pointcut and advice instances. All 15 instancesof the pointcut include Line 6 “(call(Session Session-Factory.openSession()))”; thus, one copy appears in themerged pointcut. The 15 transaction instances are createdin seven different methods whose context is captured byLines 7-14. Together with the merged code for commit-ting and aborting a transaction, the resulting aspectsuccinctly captures the “transaction concept.”

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 707

TABLE 3Aspect Refactorings Applied to the Four Case Studies

Page 11: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

5.4 Separation of Concerns

To gain a better appreciation for the impact of aspectrefactoring, this section presents data from two empiricalinvestigations. The first considers dependence metrics fromall four of the case study programs, while the second looksspecifically at JHotDraw.

Definition 1. A pair ðX;Y Þ represents a Contains Dependence ifX is a class and Y is the type of one of X’s data members.

Definition 2. A pair ðX;Y Þ represents a Uses Dependence (orsimply a Dependence) if X and Y are classes or interfaces andY is mentioned explicitly in the body of X, i.e., in declarations,allocation, or cast statements within X.

Clearly, Contains Dependences are also (Uses) Depen-dences, so the former are just a specific case of the latter.Dependences are computed as sets of pairs. This means thatwhen they are counted, the number of instances of the samepair does not matter.

The dependence metrics defined above can be justifiedintuitively as an indicator of the comprehension effortrequired to understand the base code. In fact, a lowernumber of classes/interfaces and a lower number ofrelationships among them is expected to simplify thecomprehension tasks. With regards to the understandabilityof the concern code, it should be noticed that afterrefactoring, it is encapsulated into a single modular unit(an aspect). Correspondingly, understanding and modify-ing the concern code is expected to be simplified.

Table 4 shows the number of types (classes andinterfaces) and the number of uses-dependences, dividedinto base (base-to-base, base-to-concern) versus concern(concern-to-concern, concern-to-base). The dependence me-trics are directional (see Definitions 1 and 2 above) and weare interested in those outgoing from the base code (base-to-base and base-to-concern), since they can be used tocharacterize the comprehension cost of the base code. Theeffect of refactoring is the removal of dependences directedtoward concern classes. In fact, after refactoring, the basecode is oblivious to the concern code. In the refactored code,every base-to-concern dependence becomes a concern-to-base dependence, while the other dependences remainunchanged.

The data in Table 4 indicate a substantial reduction of thenumber of types and of the number of dependences, thanksto refactoring. The only exception is PetStore, for which thebenefits of aspectization can be appreciated only at a lowergranularity level. In fact, the internal logic of the methodsinvolved in the refactorings is simplified once contractenforcing is moved to a separate aspect, although no changecan be observed in terms of number of types or intertyperelationships.

We are aware of the fact that the chosen indicators of thebenefits of refactoring are quite arbitrary and partial. Othermetrics could be taken into account (e.g., complexitymetrics of the refactored methods would account for theeffects produced on PetStore). Moreover, evaluating theoverall effects of refactoring from the point of view of thefinal user would require the execution of controlledempirical studies with human subjects, going beyond thescope of the present paper. However, this preliminaryquantitative investigation let us hypothesize benefitsassociated with a simplification of the base code and withthe modularization of the refactored concern.

The second empirical investigation shows the impact ofrefactoring on a selected part of the class diagram forJHotDraw. Fig. 11 shows the 12 classes and four interfacesinvolved in “undoing” figure transfer commands. Thediagram is dominated by two inheritance hierarchies: onerooted at AbstractCommand and the other at Undoable-Adapter. In addition, it shows the Contains and Usesdependences between classes.

The effect of refactoring the undo functionality to anaspect is shown in Fig. 11. The refactoring removes the grayportions of diagram, which includes removing 13 of 21dependences, 6 of 12 classes, and 1 of 4 interfaces. Most ofthe classes deal directly with the undo activity and theirremoval is not unexpected, but there are also two classes,StandardFigureSelection and FigureEnumerator, that areonly used in support of undo functionality. The removal of

708 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

Fig. 10. Example of merged advices from JAccounting.

TABLE 4Entities (Types) and Relationships (Dependences)

in the Base and in the Concern Code

Page 12: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

all gray elements from JHotDraw’s class diagram illustratesthe simplification of the primary functionality (base classes)achieved using aspect refactoring.

5.5 Performance

After refactoring, the four considered programs have beencompiled (using the AspectJ compiler provided by Eclipse)and run to check that they actually executed as before. Theimpact on the performance of these applications due to themigration to AOP was assessed. Three of them can be runonly interactively and during their execution the user wasunable to notice any performance change. Only one casestudy (JSpider) supports batch execution mode. It has beenused to download several Web sites in batch mode. Eachdownload was repeated using the original and the AOPversion of the code. The observed execution times showedno specific tendency. Sometimes the AOP version wasfaster, sometimes the original version was so, and some-times no difference was observed. Our conclusion is thatexecution times for this application are dominated by thenetwork latency and by the load of the involved Web

servers. The local execution time is negligible, since JSpiderspends most of its time receiving data from remote serversover the Internet.

Overall, in our four case studies, no performancedegradation was observed for the refactored AOP code.However, this cannot be generalized to arbitrary applica-tions. We are quite confident that applications whoseexecution time is dominated by user interaction or networkcommunication are likely to show no perceivable perfor-mance difference once migrated to AOP.

5.6 Size

Table 5 shows the size change associated with therefactoring of the four case studies. We measured the Linesof Code (LoC)—comments excluded—of the classes in-volved in the refactoring. The size reduction is quite limitedfor the base code. The aspect code size exceeds the decreaseobserved in the base code, since each join point gives rise tomore than one line of code (pointcut, advice, advice body)and because the aspectized expression may be only aportion of a line of code. The only exception is JAccounting,

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 709

Fig. 11. Excerpt from JHotDraw’s class diagram.

Page 13: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

to which pointcut abstraction has been applied. In the otherthree cases, the increase is negligible if compared with thetotal size of the application (see Table 1). Thus, the net sizeeffect is essentially null on the overall systems and the sameholds when it is measured for the base code only. Ifconsidered in conjunction with the dependence analysisdescribed above, the data in Tables 5 and 4 indicate that thebase code size is only marginally reduced, but that the basecode structure is substantially simplified.

5.7 Lessons Learned

The most critical phase in the migration from objects toaspects consists of enabling OO transformations. Thesereformulate the base code, so that the selected concern canbe more easily separated from the base code. They allowproper join points to be made available in the base code,letting the aspect reintroduce the concern in appropriateplaces. Untangling the concern from the base functionalitymight be a hard task (a similar result was reported byMarius Marin [24]), requiring deep understanding of thefunctionalities and code organization. Most of the ad hoc,manual OO transformations fall into this category.

Once a given code fragment is “ready” for migration (i.e.,after having applied the necessary enabling OO transforma-tions to it), the next steps are quite easy and AOP-Migratorprovides considerable guidance to the user when perform-ing them. If only one of the six available refactorings isapplicable, the transformation is usually straightforward. Ifthere is more than one possibility, the decision normally canbe made quite quickly (with the aid of the automaticallycomputed priorities). In the current migration process, theless supported part is the application of the enabling OOtransformations. If, on one hand, the end-point of theOO transformation is usually known (i.e., is one of the sixobject-to-aspect refactorings) then how to get there ofteninvolves hard decision making. Present systems providelittle guidance for undertaking such an activity; there isroom for further investigation and automated support.

From the point of view of AOSD, it is interesting to notethat only a subset of all the features provided by aspects isactually used in the migrated application. In part, this is dueto the lack of a sophisticated postprocessing which appliesaspect-to-aspect transformations in order to improve thequality of the generated code. However, we think that ingeneral a small number of aspect-oriented constructs issufficient to migrate meaningful crosscutting concernspresent in real applications. Once the execution of the basecode can be intercepted at appropriate places (begin/end ofmethod, before/after call, during exception handling, etc.),there is enough power to separate and modularize thecrosscutting concerns implemented in real applications.

The migration study was somewhat constrained by theAspectJ implementation of the AOSD principles. The

limited context exposure facilities of AspectJ forced theuse of additional OO transformations to “prepare” the codeby means of enabling OO transformations, such as ExtractMethod. These enabling transformations were also used tointroduce aspect fields serving as copies of local variables.These were eventually removed from the base code andmoved to the aspect. The limited ability of AspectJ tointercept the execution of the base code also necessitatedsome enabling transformations. However, we think that thealternative of offering more context exposure/join pointscould potentially give raise to more fragile aspect defini-tions, thus resulting in a lower quality of the aspect code.Each time we had to operate some transformation to makethe base code interceptable at the right point, we found thatit was possible to apply a very meaningful code restructur-ing that would have been advisable independently of themigration to aspects. Overall, the compromise betweenlimited code intrusion and aspect power offered by AspectJseems a reasonable one.

Evaluating the benefits produced by the separation ofselected concerns into distinct aspects is a hard task andgoes beyond the scope of the present work. However, thepreliminary results that we have gathered show that asubstantial simplification of the base code is achievedthrough refactoring. Class diagrams become much moremeaningful and understandable, since the classes and inter-class relationships pertaining to the separated concern areremoved. Moreover, a substantial number of types andintertype dependences disappears from the base code,which becomes oblivious to the extracted concerns. Quali-tatively, the code looks much more focused on its corefunctionality, which is supposed to affect positively itsunderstandability. No substantial effect on size was ob-served and, in our case studies, no detrimental effect on theperformance of the applications was experienced.

6 RELATED WORK

In the migration of existing OO code to aspects, the problemthat has received the most attention is the detection ofcandidate aspects (aspect mining) [3], [5], [13], [16], [20],[25], [28], [29], [30], [33]. The problem of refactoring [2], [4],[8], [15], [17], [23], [26], [27], [35] has been considered onlymore recently. This paper takes the results of aspect miningas its starting point and focuses on the problems associatedwith automating the refactoring process. Human guidanceis important to ensure that inherent value judgments aretaken into account.

Some of the various aspect mining approaches rely uponthe user’s definition of likely aspects, usually at the lexicallevel, through regular expressions and support the user inthe code browsing and navigation activities conducted tolocate them [13], [16], [20], [28]. Other approaches try toimprove the identification step by adding more automation.They exploit either execution traces [3], [30] or identifiers[33], often in conjunction with formal concept analysis [30],[33]. Clone detection [5], [29] and fan-in analysis [25]represent other alternatives in this category.

The works most relevant to the approach presentedherein are those by Marin [24], Hanenberg et al. [15],Monteiro and Fernandes [27], [26], Laddad [23], Gybels andKellens [14], and Tourwe et al. [32]. Marin manuallyrefactored the Undo concern present in JHotDraw fromJava to AspectJ. The primary difference between this workand that which is reported in the present paper lies in thelevel of automation. Marin’s goal was to (manually)

710 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

TABLE 5Base Code Size (LoC) before and after Refactoring,

for the Classes Subjected to Refactoring

The aspect code size is given in the last two columns.

Page 14: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

understand the degree of tangling between the Undoconcern and the base code. Marin applies preliminaryOO transformations to reduce tangling, so as to producecode which is easier to migrate in much the same way wehave done in the present paper.

Hanenberg’s work deals with the redefinition of popularOO transformations taken from Fowler [11] in order tomake them aspect-aware. This work, and the work byMonteiro and Fernandes [27], consider refactorings tomigrate from OO to AOSD and refactorings that apply toaspect code. Among them, the Extract advice refactoring [15](or Extract Fragment into Advice [27]) is automated by AOP-Migrator using the first five refactorings. Our contributionto the definition of the Extract (Fragment into) Advicerefactoring consists of the precise definition of its mechanicsin the five subcases considered in the paper. For each case,we provide details about the applicability conditions, thecontext exposure constructs, the transformation rules, aswell as the prioritization of the alternatives. Our sixthrefactoring corresponds to Laddad’s Extract ExceptionHandling [23].

Gybels and Kellens [14] and Tourwe et al. [32] useinductive logic programming to transform an extensionaldefinition of pointcuts (that merely enumerates all the joinpoints) into an intensional one. This work is complementaryto that reported in the present paper, as it focuses on theproblem of generalizing and abstracting the automatically

produced pointcuts. This is definitely a desirable supple-mentary step in the overall process.

Bruntink et al. [4] present a systematic approach forisolating crosscutting concerns and illustrate this approachby focusing on a particular concern that tends to occur quitefrequently in C code: parameter checking for NULLpointers. Since different checks are required for differentparameter kinds (input, output, in/out), the authorsadopted an extension of the C language (called PCSL) forthe explicit indication of the parameter kind and of theassociated parameter checking code. Aspect extraction andelimination are fully automated.

Additional examples of refactorings from objects toaspects are given with reference to the role played by theclasses involved in the implementation of design patterns[17] or of classes implementing so-called “aspectizableinterfaces” [31]. Behavior preservation conditions for aspectrefactorings are specified in the work of Cole and Borba [8].

The main difference between the present work and themost closely related works in the literature [15], [27], [23],[24] is AOP-Migrator’s focus on the automation of therefactoring process and its use with realistic case studies.Previous works have focused on the refactoring catalog(listing all the possibilities) and consider only small,motivating examples and manual code migration. Incontrast, rather than attempting to cover the entire spec-trum of possible refactorings, AOP-Migrator considers onlythe six refactorings that were believed to cover most of the

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 711

Fig. 12. Mechanics for refactoring: Extract End of Method.

Page 15: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

instances found in real code. The experimental resultscollected so far confirm the validity of the initial selection.Thus, this paper serves as an empirical validation of suchrefactorings and of their automated implementation. AOP-Migrator is the first publicly available object-to-aspectrefactoring tool, developed as an Eclipse plug-in. It wasused in the execution of the four case studies, whichmeasured the performance of the automated approach. Themain contribution of this work to the state of the art,consists of the assessment of the level of automation thatcan be reached in the execution of a migration task fromobjects to aspects. This extends initial work [1] by addingone more refactoring (Extract Exception Handling), byimplementing the related transformations in a publiclyavailable tool and by running additional case studies thatcorroborate our findings. Moreover, the present paper givesmore details on the mechanics of the refactorings (see theAppendix) and on the Eclipse plug-in implementing them.

7 CONCLUSIONS AND FUTURE WORK

This paper has presented an approach to refactoring OOPprograms, written in Java, into equivalent AOP programs,written in AspectJ. The paper described AOP-Migrator, atool for OOP to AOP migration, which implements theserefactorings, and illustrated its application as part of amigration strategy on four medium-sized case studies.

The results show that it is possible to migrate from OOPto AOP in a largely automated way. The refactorings areentirely automated. However, they are not always directlyapplicable, necessitating the application of enabling trans-formations which map OO programs into equivalentOO programs. These enabling transformations also can belargely automated.

The goal to completely automate the migration fromOOP to AOP is probably as undesirable as it is unachie-vable; there are some refactoring decisions which are bestleft to the human. There are also situations where, as withother transformation based work, the human is best placed

712 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

Fig. 13. Mechanics for refactoring: Extract After Call.

Page 16: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

to determine the sequence of enabling transformations thatwill allow the application of a chosen refactoring.

However, as the case studies illustrate, many of theenabling transformation steps can be automated; they relyupon standard, well-understood transformations, such asside effect removal and statement reordering. Future workwill explore the possibility of defining fully automated“transformation tactics,” which will allow the user tospecify the goals of migration from OOP to AOP at ahigher level of abstraction.

Among the other issues that are left open by the presentwork, and that we intend to investigate in the future are thedevelopment of and experimentation with more advancedpointcut abstraction techniques and the execution ofempirical studies with human subjects to evaluate thebenefits of the proposed refactorings, as perceived by thefinal users.

APPENDIX

This Appendix provides an abstract description of therefactorings presented by example in the paper. For eachrefactoring, it shows the mechanics using the syntacticclasses of the Java/AspectJ languages. Variants and applic-ability conditions are described textually.

The notation adopted to show the mechanics of therefactorings uses the following conventions: Grammar

terminals are in typewriter font (e.g., class). Syntacticclasses (nonterminals) are in italics (e.g., fds for class fields)and are subscripted so as to make them uniquely referablein the right part of the transformation. Their meanings areprovided in the Legend underneath each refactoring. Newlygenerated code is in bold italic. Transformation of theoriginal context into the exposed context is indicated by theapex (e.g., the variable identifier vid1 turned into vid01), withthe rules for context exposure underneath each figure. Thecode to be aspectized is underlined.

The context exposed by each refactoring is constrained toall and only variables that are referenced in the codefragment being aspectized. To express that, function RefVar,which gives the set of referenced variables in a given codefragment, is used.

Fig. 12 shows the mechanics of Extract End of Method.The call to be aspectized is at the end of the method. Therelated join point is intercepted by the newly generatedpointcut pidpid1, which exposes the this reference as wellas all arguments of the enclosing method (args con-struct). An after-advice restores the original invocation,using the exposed context for the call target and for theactual parameters. When local variables are involved inthe call, a copy must be kept in the aspect (creating newaspect fields, added to fdfdss2). The idiom described inSection 3 (with reference to the refactoring Extract afterCall) is used in this case.

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 713

Fig. 14. Mechanics for refactoring: Extract Conditional.

Page 17: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

The main applicability condition for this refactoring isthat every return statement must be preceded by the samecode fragment to be aspectized, or, equivalently, that asingle exit point exists in the method. The variant of thisrefactoring with the call to be aspectized at the beginningrequires using a before advice. The variant with the call atthe beginning/end of an exception handling block requiresadding the primitive pointcut handler to pipidd1.

Fig. 13 shows the mechanics of Extract after Call. Theexposed context includes the current and the target objects(This and Target) and the arguments of the called method.Local variables are exposed by copying their values intoaspect fields (see Section 3), if necessary. In addition tomatching the pattern on the left in Fig. 13 and grantingaccess to the context required to perform the aspectized call,a further applicability condition must be verified: The callused as a join point in the base code (cid2:mid2) must bepresent exactly once or must be always followed by the callbeing aspectized. For the variant Extract before Call, whenthe marked block precedes the intercepted call, a before-advice is used.

Fig. 14 shows the mechanics of Extract Conditional. At thetop level of method cid1:mid1, a conditional statementsurrounds the code to be aspectized. The base code is in theelse-branch. The extracted pointcut includes a dynamiccheck of the aspectized condition (if ðvid01Þ). Applicabilityconditions for this refactoring are the presence of thesyntactic pattern shown in Fig. 14 and the possibility toexpose the context required by the aspectized invocation(target object and actual parameters) as well as the contextrequired by the condition ðvid1Þ. Variants include thepossibility of exchanged then and else branches (thepointcut condition must be negated in this case) and thepossibility for the base code to be at the top level (not insidethe conditional statement) in method cid1:mid1. In the lattercase, the proceed construct is used to ensure the executionof the base code in the case of the aspect advice activation.

Fig. 15 shows the mechanics of Pre Return. The aroundadvice that replaces the original execution stores the returnvalue, obtained through the proceed construct, into atemporary variable, which is returned only after performingthe aspectized invocation. The temporary variable is

714 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

Fig. 15. Mechanics for refactoring: Pre Return.

Page 18: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

exposed according to the normal context exposure rules,

unless it is a local variable of mid1. In such a case, it is

declared locally in the advice body (with type tp1). It should

be noticed that the pattern in Fig. 15 includes the main

applicability condition for this refactoring: The expression

in the return statement must consist of a single variable

ðvid2Þ. When the input code does not match this condition,

it is relatively easy to transform the code so as to satisfy it

(e.g., by introducing a local variable which holds the value

to be returned). Moreover, a single return point is assumed.Fig. 16 shows the mechanics of Extract Wrapper. One of

the parameters of the call to cid4:mid2 is an object of classcid2 that wraps another object, of class cid1. In thetransformed code, the aspect intercepts the call tocid4:mid2. It exposes the unwrapped parameter ðvid3Þ and

continues the original call (via proceed) with a newwrapper object ðvid2Þ replacing the original parameter.Since the join point intercepted by the aspect is a call tocid4:mid2, the applicability condition is the same as forExtract after Call. That is, just one such call must be presentor, in the presence of multiple calls, each of them must havea wrapper object as a parameter, with all wrappers built inthe same way. As a variant, it is possible to intercept theconstruction of vid1, instead of the call to mid2 (as discussedin Section 3).

Finally, Fig. 17 shows the mechanics of Extract ExceptionHandling. The catch block for exceptions of type tp2 isremoved from the base method body, thanks to thedeclare soft construct in the aspect, which softens suchexceptions. When a SoftException is raised in the executionof the original method, an after-advice is triggered in the

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 715

Fig. 16. Mechanics for refactoring: Extract Wrapper.

Page 19: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

aspect, which runs the original exception handling code

(using the exposed context to reference the needed

locations). If stmts2 does not end with a throw or an exit

statement, it is necessary to use an around advice instead

of an after advice, so as to avoid throwing a SoftException.

ACKNOWLEDGMENTS

The authors would like to thank the anonymous referees for

their suggestions, which contributed to a substantial

improvement of the initial version of the paper.

REFERENCES

[1] D. Binkley, M. Ceccato, M. Harman, F. Ricca, and P. Tonella,“Automated Refactoring of Object Oriented Code into Aspects,”Proc. Int’l Conf. Software Maintenance (ICSM), pp. 27-36, 2005.

[2] P. Borba and S. Soares, “Refactoring and Code Generation Toolsfor AspectJ,” Proc. Workshop Tools for Aspect-Oriented SoftwareDevelopment at Conf. Object-Oriented Programming, Systems, Lan-guages, and Applications (OOPSLA), Nov. 2002.

[3] S. Breu and J. Krinke, “Aspect Mining Using Event Traces,” Proc.Automated Software Eng. (ASE ’04), pp. 310-315, Sept. 2004.

[4] M. Bruntink, A. van Deursen, and T. Tourwe, “Isolating IdiomaticCrosscutting Concerns,” Proc. Int’l Conf. Software Maintenance(ICSM), pp. 37-46, Sept. 2005.

[5] M. Bruntink, A. van Deursen, T. Tourwe, and R. van Engelen, “AnEvaluation of Clone Detection Techniques for Identifying Cross-cutting Concerns,” Proc. Int’l Conf. Software Maintenance (ICSM),pp. 200-209, Sept. 2004.

[6] G. Canfora, A. Cimitile, A. De Lucia, and G.A.D. Lucca,“Decomposing Legacy Programs: A First Step towards Migratingto Client-Server Platforms,” Proc. Sixth IEEE Int’l WorkshopProgram Comprehension, pp. 136-144, June 1998.

[7] M. Ceccato, M. Marin, K. Mens, L. Moonen, P. Tonella, and T.Tourwe, “A Qualitative Comparison of Three Aspect MiningTechniques,” Proc. 13th IEEE Int’l Workshop Program Comprehension(IWPC), pp. 13-22, May 2005.

[8] L. Cole and P. Borba, “Deriving Refactorings for AspectJ,” Proc.Fourth Int’l Conf. Aspect-Oriented Software Development (AOSD ’05),pp. 123-134, 2005.

[9] J.J. Dolado, M. Harman, M.C. Otero, and L. Hu, “An EmpiricalInvestigation of the Influence of a Type of Side Effects on ProgramComprehension,” IEEE Trans. Software Eng., vol. 29, no. 7, pp. 665-670, July 2003.

716 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, NO. 9, SEPTEMBER 2006

Fig. 17. Mechanics for refactoring: Extract Exception Handling.

Page 20: 698 IEEE TRANSACTIONS ON SOFTWARE ENGINEERING, VOL. 32, … · 2010. 8. 18. · (OOP) paradigm into Aspect-Oriented Programming (AOP). A simple set of six refactorings has been defined

[10] R. Filman and D. Friedman, “Aspect-Oriented Programming IsQuantification and Obliviousness,” Proc. Workshop AdvancedSeparation of Concerns at Conf. Object-Oriented Programming,Systems, Languages, and Applications (OOPSLA ’00), Oct. 2000.

[11] M. Fowler, Refactoring: Improving the Design of Existing Code.Addison-Wesley, 1999.

[12] E. Gamma, R. Helm, R. Johnson, and J. Vlissides, Design Patterns:Elements of Reusable Object Oriented Software, Addison-Wesley,1995.

[13] W.G. Griswold, J.J. Yuan, and Y. Kato, “Exploiting the MapMetaphor in a Tool for Software Evolution,” Proc. 2001 Int’l Conf.Software Eng. (ICSE), pp. 265-274, Mar. 2001.

[14] K. Gybels and A. Kellens, “An Experiment in Using InductiveLogic Programming to Uncover Pointcuts,” Proc. First EuropeanInteractive Workshop Aspects in Software, 2004.

[15] S. Hanenberg, C. Oberschulte, and R. Unland, “Refactoring ofAspect-Oriented Software,” Proc. Fourth Ann. Int’l Conf. Object-Oriented and Internet-Based Technologies, Concepts, and Applicationsfor a Networked World (Net.ObjectDays), pp. 19-35, Sept. 2003.

[16] J. Hannemann and G. Kiczales, “Overcoming the PrevalentDecomposition of Legacy Code,” Proc. Workshop Advanced Separa-tion of Concerns at Int’l Conf. Software Eng. (ICSE), 2001.

[17] J. Hannemann, G.C. Murphy, and G. Kiczales, “Role-BasedRefactoring of Crosscutting Concerns,” Proc. Fourth Int’l Conf.Aspect-Oriented Software Development (AOSD ’05), pp. 135-146,2005.

[18] M. Harman, L. Hu, R.M. Hierons, J. Wegener, H. Sthamer, A.Baresel, and M. Roper, “Testability Transformation,” IEEE Trans.Software Eng., vol. 30, no. 1, pp. 3-16, Jan. 2004.

[19] M. Harman, L. Hu, R.M. Hierons, X. Zhang, M. Munro, J.J.Dolado, M.C. Otero, and J. Wegener, “A Post-Placement Side-Effect Removal Algorithm,” Proc. IEEE Int’l Conf. SoftwareMaintenance (ICSM ’02), pp. 2-11, Oct. 2002.

[20] D. Janzen and K.D. Volder, “Navigating and Querying Codewithout Getting Lost,” Proc. Second Int’l Conf. Aspect-OrientedSoftware Development (AOSD), pp. 178-187, Mar. 2003.

[21] I. Kiselev, Aspect-Oriented Programming with AspectJ, 2002.[22] A.S. Klusener and C. Verhoef, “9210: The Zip Code of Another IT-

Soap,” Software Quality J., vol. 12, no. 4, pp. 297-309, 2004.[23] R. Laddad “Aspect Oriented Refactoring Series (Part 2—The

Techniques of the Trade),” http://theserverside.com, Dec. 2003.[24] M. Marin, “Refactoring JHotDraw’s Undo Concern to AspectJ,”

Proc. First Workshop Aspect Reverse Eng. (WARE ’04), Nov. 2004.[25] M. Marin, A. van Deursen, and L. Moonen, “Identifying Aspects

Using Fan-In Analysis,” Proc. 11th IEEE Working Conf. Reverse Eng.(WCRE ’04), Nov. 2004.

[26] M.P. Monteiro and J.M. Fernandes, “Refactoring a Java Code Baseto AspectJ: An Illustrative Example,” Proc. Int’l Conf. SoftwareMaintenance (ICSM), pp. 17-26, Sept. 2005.

[27] M.P. Monteiro and J.M. Fernandes, “Towards a Catalog of Aspect-Oriented Refactorings,” Proc. Fourth Int’l Conf. Aspect-OrientedSoftware Development (AOSD), pp. 111-122, Mar. 2005.

[28] M.P. Robillard and G.C. Murphy, “Concern Graphs: Finding andDescribing Concerns Using Structural Program Dependencies,”Proc. 24th Int’l Conf. Software Eng. (ICSE), pp. 406-416, May 2002.

[29] D. Shepherd, E. Gibson, and L. Pollock, “Design and Evaluation ofan Automated Aspect Mining Tool,” Proc. Mid-Atlantic StudentWorkshop Programming Languages and Systems (MASPLAS), Apr.2004.

[30] P. Tonella and M. Ceccato, “Aspect Mining through the FormalConcept Analysis of Execution Traces,” Proc. 11th Working Conf.Reverse Eng. (WCRE), pp. 112-121, Nov. 2004.

[31] P. Tonella and M. Ceccato, “Refactoring the AspectizableInterfaces: An Empirical Assessment,” IEEE Trans. Software Eng.,vol. 31, no. 10, pp. 819-832, Oct. 2005.

[32] T. Tourwe, A. Kellens, W. Vanderperren, and F. Vannieuwen-huyse, “Inductively Generated Pointcuts to Support Refactoring toAspects,” Proc. Software Eng. Properties of Languages for AspectTechnology (SPLAT) Workshop at Conf. Aspect-Oriented SoftwareDevelopment (AOSD ’04), 2004.

[33] T. Tourwe and K. Mens, “Mining Aspectual Views Using FormalConcept Analysis,” Proc. Fourth IEEE Int’l Workshop Source CodeAnalysis and Manipulation (SCAM ’04), pp. 97-106, Sept. 2004.

[34] A. van Deursen and T. Kuipers, “Identifying Objects UsingCluster and Concept Analysis,” Technical Report SEN-R9814,Centrum voor Wiskunde en Informatica (CWI), Sept. 1998.

[35] A. van Deursen, M. Marin, and L. Moonen, “Aspect Mining andRefactoring,” Proc. First Int’l Workshop Refactoring: Achievements,Challenges, Effects (REFACE), with WCRE, Nov. 2003.

[36] M. Ward, “Assembler to C Migration Using the FermaTTransformation System,” Proc. IEEE Int’l Conf. Software Main-tenance (ICSM ’99), Aug. 1999.

David Binkley is a professor of computerscience at Loyola College in Maryland, wherehe started in 1991. He began working onprogram analysis in 1988 and on aspect-oriented programming in 2000, during a sabba-tical leave from Loyola. This year with Gramma-Tech Inc., he focused on improvements toCodeSurfer. From 1993 to 1999, he worked withthe National Institute of Standards and Technol-ogy (NIST). During this time, he was part of the

team that worked on the C program slicer Unravel. His present researchinterests include projects involving aspects, testing, software qualityassessment, dependence analysis, and search based-software engi-neering. He is a member of the IEEE.

Mariano Ceccato received the degree in soft-ware engineering from the University of Padova,Italy, in 2003. His master’s thesis concerned thereengineering of an existing large-sized datawarehouse application. He is a PhD student atITC-irst in Trento, Italy. His research interestsare in source code analysis and manipulation,especially for the identification of crosscuttingconcerns in nonaspect code and for the trans-formation of object-oriented code to aspect-

oriented programming. He is a student member of the IEEE.

Mark Harman is head of the Software Engineer-ing Group at the Department of ComputerScience, King’s College, London. He is widelyknown for his work on program slicing, transfor-mation, and testing, and more recently he wasinstrumental in the founding of the field ofsearch-based software engineering. ProfessorHarman is funded by the UK Engineering andPhysical Sciences Research Council (EPSRC),the EU, and DaimlerChrysler, Berlin. He is the

director of the SEBASE project running from 2006 to 2011, a largemultisite project that will develop the theory and practice of search-based software engineering.

Filippo Ricca received the degree in computerscience in 1994 and the PhD degree in computerscience from the Computer Science Departmentof the University of Genova, Italy. From 1995 to1998, he worked at Comune di San Lorenzo alMare (Imperia, Italy) as a computer operator andaccountant. In 1999, he joined the softwareengineering group at ITC-irst. His current re-search interests include Web application analy-sis, maintenance, and testing, automatic

program transformation, extreme programming, aspect-oriented pro-gramming, and empirical studies.

Paolo Tonella received the laurea degree cumlaude in electronic engineering from the Uni-versity of Padua, Italy, in 1992, and the PhDdegree in software engineering from the sameuniversity, in 1999, with the thesis “CodeAnalysis in Support to Software Maintenance.”Since 1994, he has been a full-time researcherof the Software Engineering Group at ITC-irst,Trento, Italy. He is the author of ReverseEngineering of Object Oriented Code, (Springer,

2005). His current research interests include reverse engineering, AOP,empirical studies, Web applications, and testing. He is a member ofthe IEEE.

BINKLEY ET AL.: TOOL-SUPPORTED REFACTORING OF EXISTING OBJECT-ORIENTED CODE INTO ASPECTS 717