Reusing Reused CodeTomoya Ishihara, Keisuke Hotta, Yoshiki Higo, Shinji Kusumoto
Graduate School of Information Science and Technology, Osaka University
1-5, Yamadaoka, Suita, Osaka, 565-0871, Japan{t-ishihr, k-hotta, higo, kusumoto}@ist.osaka-u.ac.jp

Abstract—Although source code search systems are well known
as being helpful to reuse source code, they have an issue that theyoften suggest larger code than what users actually need. This isbecause they suggest code based on the structure of programming
languages such as files or classes. In this paper, we propose a newcode search technique that considers past reuse. In the proposed
technique, code are suggested at the unit of past reuse. The
proposed technique detects reused code by using a fine-grainedcode clone detection technique. We conducted an experiment tocompare the proposed technique with an existing technique. The
result shows that the proposed technique helps more effectively
to reuse code than the existing technique.
Index Terms—code search; code clone; source code reuse;

Code clone detection

Code

Clone
Clone

Clone
Clone

CRS computing

Source code set

Keyword extraction
Clone
Clone

Clone
KeywordCRS

Code analysis
Code suggestion

Reused code
information
Clone
Keyword

Code

user

I. I NTRODUCTION
In software development, it is beneficial to reuse existingsource code. If developers reuse existing source code adequately, software development efficiency rises because they do
not need to implement new functions. Besides, if they reuse
source code that has already been well tested, software obtains
high reliability easily. Consequently, it is useful to reuse codein software development. Currently, many researchers haveproposed systems helping source code reuse.
One of the systems helping code reuse is code searchsystems [1]–[3]. Code search systems suggest code related toqueries that users have input. They suggest code in the orderof own measures. Code search systems do not require complex
procedures for users. Users only need to decide queries when
they use code search systems.
However, existing code search systems have an issue. Theysuggest source code including extra functionalities that users
do not need. Hence, users must take costs to identify functions
that they actually need. This issue is caused because theysuggest source code based on structural unit of programming
languages. In particular, this issue often occurs when users
need a single or small functionality because most existing
systems suggest source code on class or file unit. Users do
not always require functionalities of the same unit or the same
abstraction level. Sometimes users require a piece of a codefragment, which consists of several lines of code, and othertimes they need code forming the whole classes. Therefore,
it is necessary for the systems to suggest source code withdifferent sizes and different abstraction levels depending on
users’ requirements.
In this research, we propose a technique that detects
reusable code that has been actually reused in the past andsuggests it to users. That is to say, conventional search engines
return entire PL units (methods, classes, files) while our

Clone
Query

Code

WOS computing

visualizer

Code

Figure 1. overview of the proposed techniqueapproach returns code snippets that were duplicated. Also,
our approach can suggest reused code even if they do nothave API invocations unlike the conventional techniques [2].
The presence of reused code means that someone needed andreused the code in the past. Hence, authors think that code
reused in the past will meet requirements of reuse in the future.
We adopt a code clone detection technique for detecting reusedcode fragments [4]. One reason why code clones occur insource code is code reuse so that detecting code clones means
detecting past code reuse.
Contributions of this paper are as follows.
• We propose a new technique that suggests reusable codethat has been reused. In the proposed technique, only
reused code is suggested to users.
• We have conducted a small experiment and confirmed theusefulness of it.
II. C ODE S UGGESTION A RCHITECTURE
A. Overview
In this research, we propose a technique that suggests
source code based on its past reuse in order to provide
reuse opportunities demanding on sizes and abstraction levelsof users’ requirements. Figure 1 shows an overview of the
proposed technique. The proposed technique analyzes target
source files and stores reused code into a database. If users
input a query into a system, they obtain reused code that are
related to the query.

The proposed technique consists of a code analysis procedure and a code suggestion procedure. In the code analysis
procedure, the proposed technique detects code clones tocollect a set of code fragments to be suggested to users. In thecode suggestion procedure, the proposed technique suggests
code fragments that are related to queries that users have input.
Before the code suggestion procedure process users’ queries,
a database of reused code must have been built by performing
the code analysis procedure. The code suggestion procedure is
performed for every users’ query meanwhile the code analysis
procedure is performed only one time to build a database ofreused code information.
B. Code Analysis Procedure
The code analysis procedure consists of the following steps.
STEP1: detecting code clones to collect a set of codefragments reused in the past.
STEP2: computing a score for every reused code fragment
based on the caller-callee relationship.
STEP3: extracting keywords in the reused code fragments.
In the proposed technique, only the code fragments reusedin the past are suggested to users. In order to identify pastreuse, we adopt a code clone detection technique. One reason
why code clones occur in source code is code reuse such as
copy and paste operations. Hence, we can find code fragmentsthat have been reused by detecting code clones from a set ofa large amount of source files.
In addition, the proposed technique computes a score foreach code fragment in order to suggest code that are suitablefor users’ requirements. In this research, we use Component
Rank technique [1] to compute scores for code fragments.
Component Rank technique computes a score for each function
based on the caller-callee relationship. A score for a codefragment is the same as the score for the function including thecode fragment. It computes a score independently on queries
that users input because it uses static information of function
calls. Also, the proposed technique considers the number ofpast reuse in computing scores. Code fragments that have beenreused many times have high scores.
C. Code Suggestion Procedure
The code suggestion procedure includes the following steps.
STEP1: finding code fragments related to queries that users
have input from the database.
STEP2: ranking code fragments based on their scores andstrength of relevance to queries
STEP3: suggesting code fragments in the ranking order.
In this research, we use two scores, Component Rank Score(CRS) and Word Occurrence Score (WOS). CRS represents
scores computed by using Component Rank technique. WOS
represents strength of relationship between code fragments andthe queries that users have input. WOS becomes high if queries
match the keywords that sufficiently indicate a functionality ofa code fragment. The proposed technique dynamically computes WOS each time users submit queries while it computes
CRS beforehand at the code analysis procedure. Finally, theproposed technique sorts code fragments suggested to users in
the order.
III. D ETAILS OF C ODE S UGGESTION
A. Code Clone Detection
In this research, we need to detect small code clones in orderto suggest code fragments on a variety of sizes and abstractionlevels. If we use a fine-grained detection technique, we candetect both small code clones such as several lines of codeand large ones such as the whole classes. However, if we usecoarse-grained detection technique such as file clone detection
technique, we can detect only large code clones. We also needto select a scalable code clone detection technique because
the proposed technique needs to detect code clones from alarge amount of source files. Consequently, we adopt an indexand statement-based code clone detection [4]. This techniquedetects code clones through the following steps.
STEP1: extracting all the statements from every method asa sequence.
STEP2: computing a hash value for every p consecutive
statements. Value p is specified by users in advance.
STEP3: detecting subsequences whose hash sequences are
the same as code clones.
The proposed technique realizes scalable code clone detections by using hash-based code matching.
B. Component Rank
The proposed technique computes a CRS score for every
code fragment by applying a variant of Component Rank(CR)[1]. CR technique computes a score for every function basedon the caller-callee relationship, by applying a variant ofPageRank, which is used to measure the relative importanceof web sites. It determines a score based on two concepts:••

functions called in many other functions are significant.
functions called in significant functions are significant.

Also, CR technique groups similar functions. CR techniqueredefines the score of the function by summing up scores offunctions that are similar to it.
In this research, the proposed technique computes a scorefor every method by using CR algorithm in order to computea score for every code clone. A score of a given code clone isdefined as the score of the method including the code clone.
C. Keyword Extraction
The proposed technique extracts keywords from code fragments. Hence, the proposed technique does not extract any
keywords from code fragments that have not been reused anddoes not suggest them to users. We extract keywords fromidentifiers such as variable names, method names, class names
and Javadoc comments attached to methods and classes. Also,
the proposed technique uses the natural language processing
such as stemming and eliminating stop words. Finally, theproposed technique stores keywords into a database.

D. Measuring Relationship between Queries and Keywords
We select TF-IDF technique as a measure of WOS. TF-IDF
technique computes a score for every term in all documents
based on two metrics, TF and IDF. A TF represents aterm frequency of a certain document. A IDF represents aninverse document frequency including a certain term. TF-IDF
technique is commonly used in search systems into whichusers input queries.
In this research, a keyword corresponds to a term and a codefragment corresponds to a document. The proposed techniquecomputes WOS by using the following formula.
Wwos (i, j) =

|D|
ti,j
× log
|Ti |
di

(1)

ti,j represents the number of frequency of term i in codefragment j• Ti represents a set of the terms i in all the code fragments• D represents a set of all the code fragments• di represents the number of documents including term i• |S| represents the number of elements included a set S
If queries match keywords extracted only from a small
number of code fragments, WOS becomes high.
•E. Merging Scores
The proposed technique derives relative importance amongcode fragments based on CRS and WOS. Code fragments aresuggested to users in the order of the relative importance.
F. Implementation
It is necessary that the proposed technique quickly detects code clones from a large amount of source files andalso quickly computes a score of code clones. Hence, we
implemented some heuristics in the proposed technique. For
example, existing systems have computed a score of eachclass by using Component Rank algorithm. On the other hand,the proposed technique needs to compute a score for every
method. The proposed technique needs much more time tocompute scores of methods because there are considerably
more methods than classes in the source files. Hence, theproposed technique computes a score of every method approximately by distinguishing between method calls within aproject and method calls across projects. This approximate
calculation is widely used [5].
IV. E XPERIMENT
A. Experimental Setup
In order to evaluate the proposed technique, we have implemented a prototype based on the proposed technique. In thissection, we called this prototype P . We applied it to target
source files and created a database. In this experiment, weused the source files that had been used in the evaluation of
SPARS as our target [1]. The target source files consist of about
190,000 Java source files, which is about 400 projects.
In addition, we have built the following two variants of the
prototypes for comparison.

A variant in which the proposed technique was implemented except considering the number of past reuse. For
example, even code that has been reused more than 10times were handled equally to the one that has beenreused only twice. We called this variant V1 .
• A variant which suggested source code based on the
structure of programming language without code clone
detection. This variant suggested code at method unit.
We called this variant V2 .
The two variants of the prototypes also were applied to thetarget source files and created databases.
•

B. Methodology
In this research, 6 participants used either of 3 tools foreach given task. Firstly, they took a lecture by the authors
for understanding given tasks and for learning how to use thetools. After the lecture, each of them independently did thetasks. For each task, they considered keywords themselves. Ifthey did not find reusable code fitting to the given tasks witha keyword, they searched code with another keyword freely.
In the experiment, we did not restrict the number of searchingcode with keywords because we search reusable code by freelychanging keywords in the real situation in code reuse. The time
limit of each task set to 20 minutes. Participants timed theircode reuse, which was from the beginning of searching code
to the completion of the task.
Three participants were master’s course students and theother 3 participants were Ph.D students of computer scienceat Osaka University. All the participants had experiences ofJava programming more than one year. The average was 2.83
years. They had no industry experiences. They were divided
into 3 groups. A pair of a master’s course and a Ph.D students
belonged to each group. Each participant was given 9 tasks.
Each group used the tool showed in Table I to complete eachtask.
C. Tasks
We used tasks that had been used to evaluate SPARS [1].
We selected 9 tasks that could be easily executed out of the
10 tasks. Also, participants determined difficulty of the giventasks into 3 levels in the experiment. Each difficulty level has
3 tasks, respectively. Table II shows a list of the tasks used inthis experiment.
D. Result
Table III shows the result of the experiment. The second,
third and fourth rows in the table mean the total times that two
participants took to complete each of the given tasks. Afterthe participants had finished all the tasks, we confirmed that
all the tasks were executed correctly. If a certain participant
TABLE ITHE TOOL THAT EACH GROUP USED TO COMPLETE EACH TASK

group1group2group3

task1,2,3
PV2
V1

task4,5,6
V1
PV2

task7,8,9
V2
V1PTABLE III
THE TOTAL TIMES THAT PARTICIPANTS TOOK TO FINISH EACH THE GIVEN TASKP
V1
V2
difficulty
best tool

task1
1,091
1,309
365
easy
V2

task2
1,393
1,109
925
easy
V2

task3
2,400
2,400
2,400
difficult
-

task4
2,400
1,994
1,508
difficult
V2

task5
1,525
367
689
easy
V1

task6
848
1,286
954
medium
P

task7
1,360
2,400
1,930
medium
P

task8
1,529
1,890
2,400
difficult
P

task9
853
2,011
240
mediumV2

could not complete the given task within the limited time,
we regarded that the participant took 20 minutes to complete
the task. The fifth row means the difficulty of each task. The
sixth row means the best tool, with which participants took
the shortest time to complete the task. For the task 3, the best
tool was not selected because no participant completed thetask within the limited time.

We compared the means of completion time for eachtechnique by using Tukey’s HSD test with significance level
α = 0.05. The result of the test showed that there were nodifferences among the means of completion time for the 3techniques. Then, we investigated which technique made thecompletion time shortest for each task. As looking at the table
III, we found that V2 was the most effective tool for users on
4 tasks. However, compared to P , V2 is the most effective
for relatively easy tasks. On the other hand, P is the mosteffective for relatively difficult tasks.
This was caused by the difference of sizes of functionalities. Difficult tasks were implemented with a combinationof multiple methods meanwhile easy tasks were implemented
with a single method. Participants using P could make aneffective combination of functionalities because P suggested
only necessary parts of methods. On the other hand, because
V2 suggested the whole methods, participants using V2 needed
to find where they should reuse. Participants had difficulties tocomplete the task 4 because of a low experience of Java applet.
Hence, this task was determined as difficult nevertheless it
could be implemented with a single method. Figure 2 shows
an example of code suggested by P , V1 and V2 . P and V1
suggested a highlighted part of the method meanwhile V2suggested the whole method that was about 200 lines of code.
In order to improve efficiency to reuse code, it is necessary thatsystems help to reuse functionalities that users takes much time
to implement. Consequently, P is useful to support reusingcode that it is difficult for users to implement.
Also, comparing between P and V1 , the participants finishedover half of all the tasks in a shorter time by using P thanby using V1 . For example, P suggested the code in Figure 2
on the top if they input a query into it, “zip deflate”. On theother hand, V1 suggested the code at the 43rd from the top.
This means that functionalities that users actually needed weresuggested on the top by considering the number of past reuse.

TABLE II

V. T HREATS TO VALIDITY

157
158
159
160

260
261
262
263
264
265
266
267
268
269
270
271

328
329

protected String streamAsset(HttpServerRequeset request,
HttpServerResponse response){//
Get Asset ID
int A_Asset_ID = WebUtil.getParameterAsInt(request, “Asset_ID”);::
ServletOutputStream out = response.getOutPutStream();
ZipOutputStream zip = new ZipOutputStream(out);//Servlet out
zip.setMethod(ZipOutputStream.DEFLATED);
zip.setLevel(Deflater.BEST_COMPRESSION);
zip.setComment(readme);// Readme File
ZipEntry entry = new ZipEntry(“readme.txt”);
entry.setExtra(assetInfo);
zip.putNextEntry(entry);
zip.write(readme.getBytes(), 0, readme.getLength());
zip.closeEntry();::
return null;}(a) output of the tools. P and V1 suggested a highlighted part of the method.
V2 suggested the whole method.
FileInputStream in = new FileInputStream(input);
ZipOutputStream zip = new ZipOutputStream(output);//out
zip.setMethod(ZipOutputStream.DEFLATED);
zip.setLevel(Deflater.BEST_COMPRESSION);//Servlet

final byte[] buf = new byte[1024];
zip.putNextEntry(new ZipEntry(input.getName()));
int len;while((len = in.read(buf)) > 0){
zip.write(buf, 0, len);}zip.closeEntry();(b) code in which a certain participant implemented the given task
Figure 2. an example of code reuse in the experiment

A LIST OF THE TASKS

task
task1
task2
task3
task4
task5
task6
task7
task8
task9

requirement
implement a quicksort algorithm
implement a binary search algorithm
build a Java applet that shows an analog clockbuild a Java applet that shows a textarea
implement a functionality of random number generation
implement functionalities of a stack such as push and pop
implement a functionality that compresses a file ora directory with ZIP format
implement a functionality that dumps a class file
implement functionalities that read an input file andwrite the copy of the file through a stream

Participants. We had 6 participants use the 3 tools andcomplete the given tasks. All the participants had experiencesof Java programming more than one year. However, if there
is a large difference of skills of Java programming among
the participants, the difference of skills has possibilities toinfluence result in this experiment. In this experiment, 6participants were divided into 3 groups. Each group consistedof 2 participants, a master’s course student and a Ph.D student.
Hence, the difference of skills among the groups should havebeen small.

Time pressure. The participants must have completed eachtask within 20 minutes. Hence, there was a possibility thatthe limited time might have pressured the participants andso some of them missed the code that should be reused andconsequently spent more time to complete the task.
Target data set. The proposed technique decides the orderof code suggestion considering the number of code clones.
Which code becomes code clones is dependent on target data
sets. Hence, it is possible that a result with another data set isdifferent from the one in this experiment.
Implementation. In this research, in order to create a
database quickly, some approximate calculations were implemented in the proposed technique. For example, the proposed
technique computed a score of every method approximately
by distinguishing between method calls within a project andmethod calls across projects. Hence, if the proposed techniquecomputed a strict score of every method by using such as ahigh performance machine, there was a possibility that theresult in this experiment varies.
VI. R ELATED W ORK
Inoue at el. proposed Component Rank(CR), which computes scores of functions based on the caller-callee relationship, and Keyword Rank(KR), which gives different weights
for each keyword based on its position in source code [1].
They also built a source code search system, SPARS [1], inwhich the above ranking algorithms were adopted. CR gives
a high score to a function called in many other functions anda function called in functions whose scores are high. Also, itmerges scores of similar functions and redefines their scores.
Hence, scores of functions to which many functions are similar
become high. KR gives scores to keywords based on theirtoken types. If the types of a given keyword is significant,its score becomes high. For example, keywords included inmethod names or class names are significant.
McMillan et al. proposed a technique that computes scoresof functions based on Navigation Model(NM) and Association
Model(AM). They built a source code search system, Portfolio,
based on their proposed technique [3]. NM represents how
programmers trace functions. It gives scores to functions basedon the caller-callee relationship, by applying a variant ofPageRank. AM represents the relationship among keywords.
It computes strength of the keyword relationship by applying
Spreading Activation. After users submit a search query, Portfolio shows a function call graph included suggested functions.
Users can learn the usage of the functions by tracing functions
with the graph and viewing their usage.
The two existing techniques are similar to the proposed
technique in terms of computing a score of every function
based on the caller-callee relationship. In addition, SPARS
merges similar functions like the proposed technique. However, the two techniques suggest source code based on the
structure of programming languages. On the other hand, theproposed technique suggests source code based on past reuse.
Hence, particularly when users are going to reuse small
functionalities, the proposed technique better than the twotechniques in terms of suggesting only the functionality thatusers actually need.
Holmes et al. proposed an approach to help pragmaticreuse [6]. It enables developers to investigate code that theywant to reuse and to integrate the code semi-automaticallyby using captured pragmatic reuse. Meanwhile the approach
supports reuse from only a system given by users, the proposed
technique suggests functionalities from a variety of systems.
VII. C ONCLUSION
This paper proposed a new technique that suggested
reusable code that had been reused in the past in order to meetthe different requirements of users. The proposed techniquecalculates the number of past reuse for each code fragment
and ranks the suggested code fragments by considering it. We
have conducted an experiment that measured and compared
the time when 6 participants completed the given task. They
completed the given tasks by using 3 tools including one inwhich the proposed technique is implemented.
The result shows that the proposed technique helps more
effectively to reuse code than a conventional technique. The
result also shows that consideration of the number of reuse in
the past contributes to the effective code reuse.
As future works, we are going to build a web-based code
search system in which the proposed technique is fully implemented. At this time, the proposed technique considers
not only the relevance to a task but also the ease of reuse.
After building it, we are going to invite more participants andconduct large scale experiments. Also, we consider that weapply the proposed technique to the code completion. If users
write code half way and execute code completion, the code thathas been reused in the past is auto-completed immediately.
ACKNOWLEDGMENTS
This study has been supported by Grants-in-Aid for Scientific Research (S) (25220003), Grant-in-Aid for Exploratory
Research (24650011), and Grand-in-Aid for Young Scientists(A) (24680002) from the Japan Society for the Promotion of
Science.
R EFERENCES[1] K. Inoue, R. Yokomori, T. Yamamoto, M. Matsushita, and S. Kusumoto,“Ranking significance of software components based on use relations,”
IEEE Transactions on Software Engineering, vol. 31, no. 3, pp. 213–225,
2005.
[2] M. Grechanik, C. Fu, Q. Xie, C. McMillan, D. Poshyvanyk, andC. Cumby, “A search engine for finding highly relevant applications,”in Proc. of the 32nd International Conference on Software Engineering,
2010, pp. 475–484.
[3] C. McMillan, M. Grechanik, D. Poshyvanyk, Q. Xie, and C. Fu, “Portfolio: Finding relevant functions and their usages,” in Proc. of the 33rd
International Conference on Software Engineering, 2011, pp. 111–120.
[4] B. Hummel, E. Jürgens, L. Heinemann, and M. Conradt, “Index-based
code clone detection: incremental, distributed, scalable,” in Proc. of the
26th International Conference on Software Maintenance, 2010, pp. 1–9.
[5] A. Z. Broder, R. Lempel, F. Maghoul, and J. Pedersen, “Efficient pagerankapproximation via graph aggregation,” Information Retrieval, vol. 9, no. 2,
pp. 123–138, 2006.
[6] R. Holmes and R. J. Walker, “Systematizing pragmatic software reuse,”
ACM Transactions on Software Engineering and Methodology, vol. 21,
no. 4, pp. 1–44, 2012.