2013 17th European Conference on Software Maintenance and Reengineering

Reordering Program Statements for Improving Readability
Yui Sasaki, Yoshiki Higo, Shinji Kusumoto
Graduate School of Information Science and Technology, Osaka University,
1-5, Yamadaoka, Suita, Osaka, 565-0871, Japan
Email: {s-yui,higo,kusumoto}@ist.osaka-u.ac.jp
for automated refactoring, however, recent studies revealed
these tools had rarely been used: one of the factors is that it is
difﬁcult for developers to predict the outcome of refactoring
tools [4]. Therefore, we consider that reordering operation
should be performed not automatically for all the modules
but interactively for only a module speciﬁed by the users.
The proposed technique is a ﬁrst step for providing aninteractive refactoring environment.

Abstract—In order to understand source code, humans
sometimes execute the program in their mind. When theyillustrate the program execution in their mind, it is necessary
to memorize what values all the variables are along with theexecution. If there are many variables in the program, it ishard to their memorization. However, it is possible to ease
to memorize them by shortening the distance between thedeﬁnition of a variable and its reference if they are separated
in the source code. This paper proposes a technique reordering
statements in a module by considering how far the deﬁnitionof a variable is from its references. We applied the proposed
technique to a Java OSS and collected human evaluations
for the reordered methods. As a result, we could conﬁrm
that the reordered methods had better readability than their
originals. Moreover, we obtained some knowledge of humanconsideration about the order of statements.

II. R ELATED W ORKBuse and Weimer investigated code readability with several software metrics [5]. Their investigation result reported
that the number of identiﬁers in each line affected readability. Also, Dunsmore and Roper reported that mental
simulation, in which humans read source code and execute the program in their mind, is useful for program
comprehension [6]. Nakamura et al. developed a model byrepresenting human short-term memory as FIFO queue, andmeasured the cost of mental simulation [3]. They reported
that appearances of variables not in the queue have negative
impacts on understanding the source code.
Recent studies presented techniques for automaticallyformatting source code in order to improve readability.
Wang et al. presented an automatic formatting tool that
identiﬁed meaningful blocks and inserted blank lines [7].
Also, prettyprinting is one of the most famous techniques toreformat coding style such as indentation and blank lines.
These studies improved readability of source code withoutchanging its program behavior. However, it is difﬁcult toreorder program statements automatically because there arevarious relationships between statements such as control
dependence, data dependence, and control ﬂow. Those relationships affect the program behavior. It has not been
conducted such a study, and also not been evaluated thereadability due to the difference of the order of statements.

Keywords-source code readability, source code analysis, software tool, arranging program statements

I. I NTRODUCTION
In order to maintain a software system, we must understand its source code. However, software understanding itself
is costly [1], [2]. For example, it is hard to understand therole and the value of a variable whose deﬁnition is separated
from its reference [3]. In order to relieve the negative impacts
caused by separated variable deﬁnitions and their references,it would be useful to move the statements of deﬁning andreferencing a variable close to each other in source code.
This paper proposes a new technique reordering statements in a module by considering how far the deﬁnitionof a variable is from its references. Also, we applied the
proposed technique to a Java OSS and investigated theusefulness of the proposed technique. As a result, we could
conﬁrm that the proposed technique identiﬁed reordering
opportunities for about 200 methods and the some of thereordered modules had better readability than their originals.
The main contributions of this paper are:• it proposes a technique to shorten the distance between
deﬁnition and reference of a variable;• it conﬁrms that reordering statements can improve readability of Java methods by conducting an experimentwith 44 subjects;• it provides some knowledge of human consideration
about the order of statements through the experiment.
We consider that reordering statements for improving
source code is a kind of refactoring. There are many tools
1534-5351/13 $26.00 © 2013 IEEE
DOI 10.1109/CSMR.2013.50

III. M OTIVATING E XAMPLE
We consider variables sgSet and nonPcSet in the sourcecode of Figure 1. Figure 1(a) shows an example that variable
deﬁnitions and their references are separated. sgSet is referenced only within the if-block beginning at the 48th line,
however it is deﬁned outside of the block. It is naturally
desirable that scope of variables is small as much as possible,
which is a principle of the variable locality. Also, though361

36: HashSet sgSet = new HashSet();…
41: HashSet nonPcSet = new HashSet();…
48: if (…) {49:
sgSet.add("caption");…
setSegments(sgSet);} …
369:nonPcSet.add(…);

sgSet
nonPcSet…
46: if (…) {47:
HashSet sgSet = new HashSet();48:
sgSet.add("caption");…
setSegments(sgSet);} …
368 HashSet nonPcSet = new HashSet();369:nonPcSet.add(…);(a) before(b) after

Figure 1.

movinginto inner block

Motivating Example
moving within
the same blockordering constraints

input ordering constraints…
view the resultinteractive operation

Figure 2.

A
B
C
D
E
F

A
C
D
F
E
B

INPUT
a module

if ((isStateChangeTriggerEvent(event))
g
gg
(
)) {
final AstToken token = event.getToken();super.entered(event);
if (this.isDefinitionToken(token)) {…
} else { … }}if (isStateChangeTriggerEvent(event)) {super.entered(event);
final AstToken token = event.getToken();if (this.isDefinitionToken(token)) {…
} else { … }}select a module
visualize the result

final AstToken token = event.getToken();if (isStateChangeTriggerEvent(event)) {super.entered(event);
if (this.isDefinitionToken(token)) {…
} else { … }}OUTPUTthe module with thereordered statements

Figure 3.

automatic reordering

An Example of Applying the Strategies

distance between the statement deﬁning a variable (s1 ) andthe statement referencing the variable (s2 ) of a DUchain as
a numeral metric1 . Herein, distance means the number ofstatements between s1 and s2 . Let distance(c) be the distanceof DUchain c, and DUchain(B) be the set of DUchains
existing in block B. Then, the total distance of the DUchainsin B is deﬁned as the following formula.

Overview of an Interactive Reordering Environment

scope of nonPcSet is not able to narrow down anymore
because its deﬁnition and reference are at the same block,
it is possible to move its deﬁnition close to its reference
like Figure 1(b). In this paper, we propose a techniquereordering program statements for improving readability ofthe source code. Speciﬁcally, we present following tworeordering strategies.
• moving statements into inner blocks in order to narrow
down variable scope (strategy 1)• moving statements close to each other within thesame block in order to shorten the distance between
a variable deﬁnition and its reference (strategy 2)

DataDistance(B) =∑distance(c)c∈DUchain(B)B. Overview of the proposed technique
The proposed technique uses AST generated from input
source code of a module. Speciﬁcally, it applies the tworeordering strategies to every program block in the input
module with a post-order traversal for the AST. Figure
3 represents an example of applying the two reordering
strategies to the if-block beginning at the 2nd line.
• At ﬁrst, if there are statements whose variable scope
can be narrowed down, they are moved into the inner
the if-block.
• Then, the proposed technique moves statements close
to each other within the if-block in order to shorten
DataDistance value of the if-block.

IV. P ROPOSED M ETHOD
The purpose of our study is supporting refactoring interactively. Figure 2 shows an overview of an interactive
refactoring environment that we are going to develop. At
ﬁrst, a user selects a module where she wants to improvereadability. Then, the tool automatically reorders the statements with primary ordering constraints (as described later)and visualizes only one result to her. If she satisﬁes theresult, she adopts it. However, if, not, she inputs her special
intention for ordering statements as new ordering constraints.
Such an interactive analysis for the module lasts until she
satisﬁes the reordering result.
In the remainder of this section, we describe the automatic
reordering technique for program statements.

C. Implement of strategies
1) Strategy 1: Statement s is moved into inner block B
if all the following conditions are satisﬁed:• s locates outside of B;• s is a variable declaration statement;• s is included in all execution paths to B;• all the variables deﬁned in s are referenced only in B;• all the variables deﬁned in s are not re-deﬁned in all
execution paths to B.
The goal of the strategy is only to narrow scope ofvariables down. Consequently, we move such a statement

A. Preliminaries
We identify Def-Use chain (DUchain) in a module byusing data ﬂow analysis technique. A DUchain is identiﬁed
from every pair of deﬁnition and reference. If a variable isreferenced twice, two chains are identiﬁed. Then, we use a

1 If a variable points to an object whose state is changed by a method
call, we regard that the variable is deﬁned and referenced.

362

{

S
S
S y
S

this.init();if (…) {return;}int x = getX();
int y = getY();
if (…) {x = getZ();}o.set(x,y);}(a) source code

Figure 4.

proposed > original

Constraints
returnxx

50s

Def-Use

Def-Def

Escape

S

{}

{}

{S }

S

{}

{}

{S , S , S , S }

S

{S }

{S }

{}

S

{S }

{}

{}

S

{S }

{}

{}

S

{}

{}

{}

# of subjects

S
S

40

original

234

30
20

no difference 184

10

proposed

0462

methods

Figure 5.

Result of All the Target Methods(b) constraints of each statement

V. C ONTROLLED E XPERIMENT
We implemented a software tool based on the proposed
technique. Currently, the tool can handle Java language. We
applied the tool a Java system, TV Browser, in this experiment. The system includes approximately 3,700 methods
that include two or more statements.
By applying the tool to all the methods, we obtained
reordering candidates from 215 methods. In order to evaluate
the usefulness of the proposed technique, we selected 20
methods as the evaluation target methods from all thereordered methods because it was unrealistic that humans
judged all the 215 methods manually.
Then, we made a questionnaire on the web. In thequestionnaire, every subject selected one of the following
options for every target method.
• A is easier to read than B;• B is easier to read than A;• There is no difference between A and B in readability.
We had manually conﬁrmed that every target method
had kept their behavior before the questionnaire because
currently the proposed technique does not completely guarantee behavior preservation. In the questionnaire, we did notinform the subjects about what strategies of reordering were
and which the original was. Additionally we removed all
blank lines and comments for all the target methods andstandardized their formats such as indents and line breaks.
We gathered subjects by social networks, and 44 subjects
were joined. Eight subjects had programming experienceswith less than 1,000 lines of Java code, 23 subjects from
1,000 to 10,000 lines, and 13 subjects more than 10,000
lines. Also, at least 28 subjects had used Java in theiracademic research and at least 12 subjects in their work.

Example of Order Constraints

to the beginning of the inner block without considering its
appropriate place in the inner block.
2) Strategy 2: The proposed technique creates all thesequences of statements that satisfy the constraints that
does not change the behavior of the program (primaryconstraints) in the ﬁrst step of the strategy 2.
The primary constraints are the followings. Herein, we
describe the constraints with Figure 4 as an example. SA.. SF in Figure 4(a) are statements in the focused block.
Figure 4(b) represents that each statement has a set ofstatements which must appear after the statement based oneach constraint.
Def-Use Constraints: two statements in a DUchain haveto keep their present order: i.e., SF references y deﬁned at
SD . If their order is reversed, SF cannot reference y.
Def-Def Constraints: if a statement references a variable
deﬁned at multiple statements, the present order of thosestatements must be kept: i.e., SF references x deﬁned at SC
and SE ; if the order of SC and SE is reversed, SF cannot
reference x deﬁned at SE because SC re-deﬁnes x.
Escape Constraints: if a statement includes jumpinstruction such as return, break, or continue-statement, thepresent order between each of the other statements and it
must be kept: i.e., SB (which is if-block) includes returnstatement, and so SC , SD , SE and SF are not always executed
depending on a conditional expression of B, but SA is always
executed; if the orders between these statements and SB arereversed, the execution conditions are changed.
Then, we describe how the strategy 2 is performed withthe above three constraints as follows:
1) creating all the sequences satisfying all the constraints;
2) extracting the sequences whose DataDistance are minimum in all the sequences.
If there are multiple minimum sequences, we apply:3) choosing only one sequence whose order is the mostsimilar to its original.
In step 3, we use Spearman’s rank correlation coefﬁcient.
That is, the correlation between each of all the sequences
obtained in step 2 and the original one is measured, and thenthe sequence whose correlation coefﬁcient is the highest,
which means the sequence is the most similar to the original
one, is selected as a result of the strategy 2.

A. Result
Figure 5 shows the breakdown of the answers from the 44
subjects for each target method. All the answers of all thesubjects are aggregated based on the values. We found that
16 out of the 20 methods had more subjects who answered
reordered method was easier to read than their originals.
Herein, we performed statistical testing for the result byWilcoxon signed-rank test, and then we conﬁrmed that there
is a signiﬁcant difference between the number of subjects
who selected reordered method and who selected originalone. This result shows that the proposed technique enables
to improve the readability of source code.

363

DUchainmContent

1

mTimeBlockSizeSp
mTimeBlockShowWestChB

1
1
1

mTimeBlockSizeSp = new JSpinner(…);
mTimeBlockShowWestChB = new JCheckBox(…);
mContent = new JPanel(…);
4
mContent.add(…);
mContent.add(mTimeBlockSizeSp, …);
mContent.add(mTimeBlockShowWestChB, …);return mContent;

1
2

4
2
1

mContent = new JPanel(…);
mContent.add(…);
mTimeBlockSizeSp = new JSpinner(…);
1
mContent.add(mTimeBlockSizeSp, …);
mTimeBlockShowWestChB = new JCheckBox(…);
mContent.add(mTimeBlockShowWestChB, …);return mContent;(b) after(a) before

Figure 6.

1

A Method Where Most of the Subject Judged as Difﬁcult

B. Discussion

opportunities reordering statements from 215 methods. Besides, we conducted an experiment with 44 subjects.The
experimental results revealed that reordered methods had
better readability than their originals in most cases. In
addition, we obtained a knowledge that not only the distance
between variable deﬁnitions and their references but alsosimilarity of consecutive statements are important factor inconsidering the order of statements.
In the future, we are going to:• collect the more factors on ordering statements;• improve our technique based on them;• develop an interactive reordering environment.

In the experience, original methods were judged to beeasier to read than their reordered ones in 4 out of the
20 methods. We investigated details of these 4 methods
carefully, and obtained following characteristics.
• There are consecutive invocations of the same method
for the same object.
• There are consecutive declarations of variables whosenames are similar to one another.
They have a common point that a similar sequence ofstatements is considered to be one of the factors improving
the readability. For example, Figure 6 shows a method
where most of the subjects judged that the original waseasier to read than the reordered. The arrows in the ﬁgure
represent DUchains, and their labels represent their distances. In Figure 6(a), there are consecutive invocationsof the same method for an object named mContent. The
proposed technique moved two variable deﬁnitions at the
beginning of the method close to their references. Many of
the subjects judged Figure 6(a) that included consecutive
mContent.add(. . .) to be easier to read than Figure 6(b) inwhich deﬁnitions and references of the two variables wereplaced consecutively.
Hence, it seems that not only the distance between variable deﬁnitions and their references but also similarity ofconsecutive statements is an important factor of appropriateness of statement reordering.

ACKNOWLEDGMENT
This study has been supported by Grants-in-Aid for
Scientiﬁc 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] A. Goldberg, “Programmer as reader,” IEEE Software, vol. 4,
no. 5, pp. 62–70, Sep. 1987.
[2] A. J. Ko, B. A. Myers, M. J. Coblenz, and H. H. Aung, “An
exploratory study of how developers seek, relate, and collectrelevant information during software maintenance tasks,” IEEE
Trans. Softw. Eng., vol. 32, no. 12, pp. 971–987, Dec. 2006.
[3] M. Nakamura, A. Monden, T. Itoh, K. Matsumoto, Y. Kanzaki,
and H. Satoh, “Queue-based cost evaluation of mental simulation process in program comprehension,” in Proc. of 9thIEEE International Software Metrics Symposium, Sep. 2003,
pp. 351–360.

VI. F UTURE W ORKFirst of all, we are going to collect the other factors
on ordering statements affecting the readability of sourcecode with more experiments, and brush up the proposed
reordering technique with them. Besides, we are going todevelop an interactive environment for supporting reordering
statements. In the environment, we are also going to put afunction that users can specify their special intentions forordering statements as new ordering constraints, such thatconsecutive statements in the original source code are kept
the original order during the reordering.

[4] M. Vakilian, N. Chen, S. Negara, B. A. Rajkumar, B. P. Bailey,
and R. E. Johnson, “Use, disuse, and misuse of automatedrefactorings,” in Proc. of the 2012 International Conference
on Software Engineering, Jun. 2012, pp. 233–243.
[5] R. P. L. Buse and W. R. Weimer, “Learning a metric for codereadability,” IEEE Trans. Softw. Eng, vol. 36, no. 4, pp. 546–
558, Jul. 2010.
[6] A. Dunsmore and M. Roper, “A comparative evaluation ofprogram comprehension measures,” The Journal of Systems
and Software, vol. 52, no. 3, pp. 121–129, Jun. 2000.

VII. C ONCLUSION[7] X. Wang, L. Pollock, and K. Vijay-Shanker, “Automatic segmentation of method code into meaningful blocks to improvereadability,” in Proc. of the 18th Working Conference on
Reverse Engineering, Oct. 2011, pp. 35–44.

This paper presented a technique reordering statements toimprove readability of source code. We applied the proposed
technique to a Java system, and then we could identify

364