Move Code Refactoring with Dynamic Analysis
Shuhei Kimura, Yoshiki Higo, Hiroshi Igaki and Shinji Kusumoto
Graduate School of Information Science and TechnologyOsaka University
1-5, Yamadaoka, Suita, Osaka, 565-0871, Japan
Email: {s-kimura, higo, igaki, kusumoto}@ist.osaka-u.ac.jp
Abstract—In order to reduce coupling and increase cohesion,
we refactor program source code. Previous research efforts forsuggesting candidates of such refactorings are based on static
analysis, which obtains relations among classes or methods
from source code. However, these approaches cannot obtainruntime information such as repetition count of loop, dynamic
dispatch and actual execution path. Therefore, previous approaches might miss some refactoring opportunities. To tackle
this problem, we propose a technique to find refactoring
candidates by analyzing method traces. We have implemented
a prototype tool based on the proposed technique and evaluated the technique on two software systems. As a result,
we confirmed that the proposed technique could detect somerefactoring candidates, which increase code quality.
Keywords-refactoring; dynamic analysis; Move Method
refactoring; software maintenance

I. I NTRODUCTION
In the case of a large project, it is difficult to keephigh quality of software design because many programmers
develop code to satisfy various requirements [1]. To solve theproblem, we apply refactoring to source code. Refactoringis a technique for improving software quality of design andis defined as “does not alter the external behavior of thecode, yet improves its internal structure” [2]. Until now,
many refactoring support techniques have been proposed,
and they are based on static analysis [3], [4].
Dynamic analysis is a technique that analyzes the data
gathered during “program executions”, instead of analyzing
its source code. Through executing a program, we can obtainan actual program behavior, which cannot be obtained fromits source code. For example, the number of invocations ofevery method, results of dynamic dispatch, actual method
invocation sequences, and so on.
In this paper, we propose a technique to detect refactoring
candidates by analyzing method traces. A method trace isa log containing sequential method invocations in program
execution. Our proposed technique detects irregular methods
in the same class as refactoring candidates. Herein, an irregular method means that it appears in different phases [5]. The
quality of source code increases by moving these methods toappropriate classes because they cooperate with one anotherin a program execution. In other words, static structure ofsource code correspond to dynamic functionalities.

978-1-4673-2312-3/12/$31.00 c 2012 IEEE

We have implemented a prototype tool based on the proposed technique and evaluated it on two software systems.
As a result, we confirmed that the proposed technique candetect some refactoring candidates which can increase code
quality by moving them. This paper makes the following
contributions:
A new refactoring support technique. Our techniqueanalyzes method traces to detect refactoring candidates. This approach enables us to detect refactoring
candidates based on the relationship between methods
in program executions. It means that we can refactor
elements detected in a program execution (e.g. types,methods actually called).
• Visualization. We visualize the phase data of methods
to find refactoring candidates easily. The visualization
also makes possible to understand characteristics ofrefactoring candidates.
•II. BACKGROUND
Tsantalis et al. proposed a methodology to identify Move
Method refactoring opportunities by solving many commonFeature Envy bad smells from source code [3]. They defined
the Jaccard distance between an entity (attribute or method)
and a class enabling the direct extraction of refactoringsuggestions. Besides, Tip et al. proposed refactoring methodology based on type constraint [4]. This technique calculates
relations between types of variables in source code. They
present the Extract Interface, Generalized Declared Type,
Infer Generic Type Arguments refactorings in the paper.
Like those works, previous approaches detect refactoring
candidates by analyzing source code. However, those methods, which are based on static analysis, did not consider
how program elements cooperate with one another in program execution, so that those techniques might miss somerefactoring opportunities. For example, there is a problem
that we cannot obtain results of dynamic dispatch by using
static analysis. We show an example code of this problem
in Figure 1, which is a piece of code that a dynamic
dispatch appearing in a clone detector. This code shows aproblem of static analysis that we cannot get information of“which instance of class ComparatorhTi is assigned to s”.

class SearchFiles{
static class FileSort implements Comparator<File>{
public int compare(File src, File target){int diff = src.getName().compareTo(target.
getName());
return diff;}}...
private static void ListPath(File dir) {// dynamic dispatchif( target.isFile() )s = new FileSort()else
s = new ArraySort()
Arrays.sort(fs, s);}}Test CaseStep 1

Executable
Jar

Refactoring
Candidates

Figure 3.
Figure 1.

MethodTrace

Step 3
DividedMethod
Trace

Step 50 4 2
8 0 0
7 0 0
7 0 0
1 0 9

Phase Count
Data
Step 4Phase Count
View
Overview of the proposed technique.

An example of code that using dynamic dispatch.

Phase

Program
Execution

Step 2

Syntactic
Analysis

Clone
Detection

ResultPrinting

FileOpen(), BuildingAST(),CountEachElement(), ...
Figure 2.

An image of phase.

In consequence, previous approaches might miss some ofrefactoring opportunities.
Our proposed technique uses dynamic analysis for identification of refactoring candidates. This technique may
identify refactoring candidates, which are hard to be detectedby the technique using static analysis, so our technique iscomplementary to previous approaches. The objective of thisresearch is to reveal the following question:
Research Question: Can we identify refactoring opportunities by using dynamic analysis?
III. P HASE
According to [5], a program execution is composed ofmultiple functions, and a gathering of methods that represents meaningful processing is named phase. Figure 2 isan image of phases. In this figure, the program execution
divided three phases: Static Analysis, Clone Detection andResult Printing. Each phase consists of method invocations
which is used for realizing a function. In the case of “StaticAnalysis” phase, there are file-open method, AST building
method, element counting method, and so on. The reason
described above, a method appearing in different phasesmeans that it is used for different functionalities.
There is a tool to detect phases automatically, named
Amida [6]. Amida detects phase-changing-point from amethod trace and divides it into multiple phases. By dividing

method traces, the phases reflect how a program is executed,
such as repetition count and dynamic dispatch.
The large number of divided phases means that each phaserepresents detailed functions. According to [6], the precisionof phase detection is over 90% when the number of output
phases is below the actual number of phases in a methodtrace. In this research, our technique visualizes phase data, sotoo many number of phases prevents us detecting refactoring
candidates. Thus, we adjusted the number of phases to nearly10, for realizing the two requirements: precise phase divisionand number which is easy to see after visualizing.
IV. P ROPOSED T ECHNIQUE
In this section, we describe steps for obtaining refactoring
candidates. Figure 3 shows the overview of the proposedtechnique. The inputs of our technique is an executable Jar
file and a test case. The proposed technique detects Move
Code refactoring candidates with the inputs.
We have to decide test cases in advance because we needtest cases to use dynamic analysis techniques. The more test
cases we prepare, we can obtain results in more detailed.
However, execution of many test cases needs much time.
Thereby, we use only one test case in this paper.
The steps of the proposed technique are as follows.
(Step 1&2) Obtain a method trace and divided method
trace: We obtain a method trace by running the given
program with the given test case. After that, divide it into
multiple method traces which represents a phase.
(Step 3) Count invocations of each method in the same
phase: In a method trace, there are invocations of the same
method repeatedly appears. In this step, we count the numberof appearance of each method per phase by using the divided
method trace which are obtained in the previous step. As aresult, we obtain “phase count data”, which is the sequenceof counted numbers of method invocations per phase.
(Step 4) Visualize phase count data: In this step, wevisualize a phase count data (obtained in Step 3). The
technique how to visualize the phase count data are asfollows.

Figure 4.

An example of a part of tool output.

We define a class as c, and methods belonging to class c
as m0 , m1 , ..., mn , the number of phases as N , the numberof invocations of mi in the phase a as pia . Additionally, thesum of all counts of a method as Pi , given by
Pi =NXpik(1)k=0

We convert the number of methods invocations per phase
into the depth of color. When the number of invocation ofphase a in mi is pia , the ratio of the color depth (p0ia ) isgiven bypi(2)p0ia = aPi
We render p0i0 , p0i1 , ..., p0iN in the same line as cells which
are filled with each color depth. We repeat this step withincrementing i from 0 to n.
As a result, we obtain “phase count view”. An exampleof this output is Figure 4. As we can see, a method nameand a sequence of colored cells are displayed in each line.
Additionally, deep color represents many invocations ofthe method in the phase, so the method is specialized thefunction of the phase.
(Step 5) Detect refactoring candidates: We detect refactoring candidates by using the phase count view (obtainedin Step 4). The detailed step how to detect refactoring
candidates are as follows.
First, we classify methods in a class with their patternof the depth of color. For example, there are four methods
in Figure 4. “makeList”, “convertPhase”, “adjust” have asimilar pattern, and the pattern of “detectClone” is different
from those three methods. Thus, there are two classification:
one is a pattern that P3-P5 are filled, and another is a patternthat only P1 is filled. Next, we detect minority classification
as irregular methods, and they are refactoring candidates.
In Figure 4, “detectClone” is an irregular method and a
refactoring candidate of Move Method refactoring.
Methods which have different patterns are used in different functionalities, thus, they should be moved to different
classes if they are minority in a class. We discover irregularmethods in terms of appearance of the phase count view,and each of them is regarded as a refactoring candidate.

Figure 5.

The output for FRISC.

After the technique: If the candidates which have a uniquepattern of all patterns, they should be moved to a newpackage. If the pattern of the candidates exists in other class,the candidates should be moved to the class which has thesame pattern (Move Method refactoring). The candidates
are methods, but if all methods in a class are the samecandidates, the class should be moved to other package (thatis to say, Move Class refactoring). Additionally, when allclasses in a package are the same candidates, it can say
the same thing (that is to say, Move Package refactoring).
Like this, our technique supports detecting candidates ofrefactorings which moves a piece of code (Move Coderefactoring), and the unit of moving is method, class orpackage.
V. E VALUATION AND D ISCUSSIONA. Experimental Design
The proposed technique has been evaluated on two software systems, “FRISC” [7] and “MASU” [8]. FRISC isa code clone detector written in Java language. That is arelatively small software which has 8 files, 846 lines ofcode, and 21 methods. On the other hand, MASU is ametrics measurement tool written in Java language. That is alarger software than FRISC, which has 1,153 files, 133,045
lines of code, and 3,957 methods in the newest version.
We prepared one test case for each target with their basic
functionality. We suggest refactoring candidates detected byour technique to developers, and questioned whether therefactoring candidates are appropriate.

B. ResultFigure 5 is a visualization result of our technique for
FRISC. We found 7 methods in FRISC and 58 methods
in MASU as refactoring candidates.
1) FRISC: According to Figure 5, there are four groups:
classes used only in P0 (green), classes used only in P1(blue), classes used in P2-P6 (red), methods only using inP6 (yellow). Blue pattern has 11 members of 18 methods, soother groups (7 methods) are judged minority and refactoring
candidates. For example, “SearchFiles.java” showed as green
in Figure 5 is a refactoring candidate, and suggest moving
them into a new package to separate functionalities. We
suggested those refactoring candidates to the developers, asa result, we obtained developers’ consent to our refactoring
candidates. Note that we remove “main” method from refactoring candidates because it is called only once in program
execution.
2) MASU: We found various refactoring candidates forMASU. In this paper, we discuss detected refactoring candidates only in a package “main.data.target.unresolved”.
In this package, we found 5 refactoring candidates.
Three candidates are classes, “JavaUnresolvedExternalFieldInfo”, “JavaUnresolvedExternalClassInfo”, and “JavaUnresolvedExternalMethodInfo”. The residual candidates aremethods, “addModifier” and “getModifiers”. We discussthem as a special feature of class names of this package.
This package has 99 classes, and 58 classes appeared in
the method trace. 3 classes have a prefixed string “JavaUnresolvedExternal”, 54 classes have a prefixed string “Unresolved”, and the last is “NameResolver”. We have detected
all files prefixed “JavaUnresolvedExternal” as refactoring
candidates, and we obtained developers’ consent to thesecandidates. However, we also detected getter and settermethods as refactoring candidates. In general, setter methods
are invoked in the initial stage of program execution, andgetter methods are invoked in the latter half of program
execution. Such methods separately appearing in method
trace, but it is better design to gather them in the same class.
Hence, such methods deem to be refactoring candidates byusing our technique, but they are false positive.

method traces by running different test cases. Additionally,
the number of phases affects the detection of refactoring
candidates. Thus, the precision of detecting refactoring candidates depends on how to detect phases.
VI. C ONCLUSIONS AND F UTURE W ORKThis paper addresses the question whether we can detect
refactoring candidates by using dynamic analysis. To answer
this question, we proposed the technique and evaluated it
on two real software. As a result, we confirmed that ourproposed technique could detect refactoring candidates.
Our future work focuses on four directions. First, we will
have quantitative comparison to the other result based on
static analysis. Second, we will create a tool to combine
results which can be obtained by using multiple test cases,
for improving the precision of our technique. Third, we will
apply dynamic analysis to other execution traces (e.g. accesstrace of variables). Finally, we will experiment with large
open source software.
ACKNOWLEDGMENT
This study has been supported by Grants-in-Aid for
Scientific Research (A) (21240002), Grant-in-Aid for Exploratory Research (23650014, 24650011), and Grand-inAid for Young Scientists (A) (24680002) from the Japan
Society for the Promotion of Science.
R EFERENCES[1] S. Eick, T. Graves, A. Karr, J. Marron, and A. Mockus, “Doescode decay? assessing the evidence from change management
data,” IEEE Trans. Software Eng., vol. 27, no. 1, pp. 1–12,
Jan/Feb 2001.
[2] M. Fowler, K. Beck, J. Brant, W. Opdyke, and D. Roberts,
Refactoring: Improving the Design of Existing Code. Pearson
Education, 1999.
[3] N. Tsantalis and A. Chatzigeorgiou, “Identification of movemethod refactoring opportunities,” IEEE Trans. Software Eng.,
vol. 35, no. 3, pp. 347–367, May/June 2009.
[4] F. Tip, R. M. Fuhrer, A. Kiezun, M. D. Ernst, I. Balaban,
and B. D. Sutter, “Refactoring using type constraints,” ACM
TOPLAS, vol. 33, no. 3, April 2011.

C. Answer to the research question
We discuss the research question, which is mentioned inSection II. In the proposed technique, we use a method
trace which represents program behavior. In the evaluation,
we found 7 (7) methods in FRISC and 58 (39) methods in
MASU as refactoring candidates. Note that the numbers ofrefactoring candidates consented by developers are parenthesized. Thus, our proposed technique is effective in thedetection of refactoring candidates.
D. Threats to Validity
In the evaluation, we use only one test case. However,method traces depend on test cases; thus, we obtain different[5] S. P. Reiss, “Dynamic detection and visualization of software
phases,” in WODA, May 2005, pp. 1–6.
[6] T. Ishio, Y. Watanabe, and K. Inoue, “Amida: a sequence diagram extraction toolkit supporting automatic phase detection,”in ICSE, May 2008, pp. 969–970.
[7] H. Murakami, K. Hotta, Y. Higo, H. Igaki, and S. Kusumoto,“Folding repeated-instructions for improving token-based code
clone detection,” in SCAM, Sep 2012, to be published.
[8] Y. Higo, A. Saitoh, G. Yamada, T. Miyake, S. Kusumoto, andK. Inoue, “A pluggable tool for measuring software metrics
from source code,” in IWSM/MENSURA, Nov 2011, pp. 3–12.