]> git.uio.no Git - ifi-stolz-refaktor.git/blame - thesis/master-thesis-erlenkr.tex
Thesis: adding motivation
[ifi-stolz-refaktor.git] / thesis / master-thesis-erlenkr.tex
CommitLineData
c8088eec 1\documentclass[USenglish,11pt]{ifimaster}
571ef294 2\usepackage{import}
7c28933b 3\usepackage[utf8]{inputenc}
9ff90080 4\usepackage[T1]{fontenc,url}
3510e539 5\usepackage{lmodern} % using Latin Modern to be able to use bold typewriter font
b4e539f7 6%\usepackage{mathpazo}
9ff90080 7\urlstyle{sf}
128adb4f 8\usepackage{listings}
58467004 9\usepackage{booktabs}
4e468834 10\usepackage{tabularx}
d11bcf4d
EK
11\usepackage{tikz}
12\usepackage{tikz-qtree}
5e5908eb 13\usetikzlibrary{shapes,snakes,trees,arrows,shadows,positioning,calc}
ae138b9d
EK
14\usepackage{babel,textcomp,csquotes,ifimasterforside}
15
16\usepackage{varioref}
79d5c2a9 17\usepackage[hidelinks]{hyperref}
8b6b22c8 18\usepackage{cleveref}
b4a197fd 19\usepackage[xindy]{glossaries}
ae138b9d 20
4ea21603 21\usepackage[style=alphabetic,backend=biber,doi=false,isbn=false]{biblatex}
12c254af 22\usepackage{amsthm}
3471cd15 23\usepackage{mathtools}
0ab2e134
EK
24\usepackage{graphicx}
25% use 'disable' before printing:
26\usepackage[]{todonotes}
0d7fbd88
EK
27\usepackage{xspace}
28\usepackage{he-she}
b289552b 29\usepackage{verbatim}
ddcea0b5 30\usepackage{minted}
347ed677 31\usepackage{multicol}
ddcea0b5 32\usemintedstyle{bw}
53be7239
EK
33
34\def\mintedframesep{11pt}
35
8fae7b44
EK
36\usepackage{perpage} %the perpage package
37\MakePerPage{footnote} %the perpage package command
9ff90080 38
6c51af15 39\theoremstyle{definition}
12c254af 40\newtheorem*{wordDef}{Definition}
3471cd15 41\newtheorem*{theorem}{Theorem}
12c254af 42
ddcea0b5
EK
43\graphicspath{ {./figures/} }
44
8b6b22c8 45\newcommand{\citing}[1]{~\cite{#1}}
e123ab03
EK
46%\newcommand{\myref}[1]{\cref{#1} on \cpageref{#1}}
47\newcommand{\myref}[1]{\vref{#1}}
4306ef44 48\newcommand{\Myref}[1]{\Vref{#1}}
8b6b22c8 49
b4a197fd 50%\newcommand{\glossref}[1]{\textsuperscript{(\glsrefentry{#1})}}
20bcc7bf
EK
51%\newcommand{\gloss}[1]{\gls{#1}\glossref{#1}}
52%\newcommand{\glosspl}[1]{\glspl{#1}\glossref{#1}}
53\newcommand{\gloss}[1]{\gls{#1}}
54\newcommand{\glosspl}[1]{\glspl{#1}}
fe0a4c48 55
12c254af 56\newcommand{\definition}[1]{\begin{wordDef}#1\end{wordDef}}
8b6b22c8 57\newcommand{\see}[1]{(see \myref{#1})}
137e0e7b
EK
58\newcommand{\explanation}[3]{\noindent\textbf{\textit{#1}}\\*\emph{When:}
59#2\\*\emph{How:} #3\\*[-7px]}
4e135659 60
128adb4f 61%\newcommand{\type}[1]{\lstinline{#1}}
03674629
EK
62\newcommand{\code}[1]{\texttt{\textbf{#1}}}
63\newcommand{\type}[1]{\code{#1}}
f041551b
EK
64\newcommand{\typeref}[1]{\footnote{\type{#1}}}
65\newcommand{\typewithref}[2]{\type{#2}\typeref{#1.#2}}
66\newcommand{\method}[1]{\type{#1}}
67\newcommand{\methodref}[2]{\footnote{\type{#1}\method{\##2()}}}
68\newcommand{\methodwithref}[2]{\method{#2}\footnote{\type{#1}\method{\##2()}}}
3510e539 69\newcommand{\var}[1]{\type{#1}}
9ff90080 70
fe0a4c48
EK
71\newcommand{\name}[1]{#1}
72\newcommand{\tit}[1]{\emph{#1}}
73\newcommand{\refa}[1]{\emph{#1}}
74\newcommand{\pattern}[1]{\emph{#1}}
75\newcommand{\metr}[1]{\emph{#1}}
76\newcommand{\ExtractMethod}{\refa{Extract Method}\xspace}
77\newcommand{\MoveMethod}{\refa{Move Method}\xspace}
78\newcommand{\ExtractAndMoveMethod}{\refa{Extract and Move Method}\xspace}
b5c7bb1b 79
1c521a77 80\newcommand{\m}[1]{$#1$}
46f52f52 81
7125ceac 82\newcommand\todoin[2][]{\todo[inline, caption={#2}, #1]{
4e135659
EK
83\begin{minipage}{\textwidth-4pt}#2\end{minipage}}}
84
cbc3b044 85\title{Automated Composition of Refactorings}
b4d90424 86\subtitle{Implementing and evaluating a search-based Extract and Move Method
01d46361 87refactoring}
7c28933b
EK
88\author{Erlend Kristiansen}
89
fe0a4c48
EK
90\makeglossaries
91\newglossaryentry{profiling}
92{
93 name=profiling,
94 description={is to run a computer program through a profiler/with a profiler
95 attached}
96}
20bcc7bf
EK
97\newglossaryentry{profiler}
98{
99 name=profiler,
100 description={A profiler is a program for analyzing performance within an
101 application. It is used to analyze memory consumption, processing time and
60065669 102frequency of procedure calls and such}
20bcc7bf
EK
103}
104\newglossaryentry{xUnit}
105{
106 name={xUnit framework},
107 description={An xUnit framework is a framework for writing unit tests for a
108 computer program. It follows the patterns known from the JUnit framework for
109 Java\citing{fowlerXunit}
110 },
111 plural={xUnit frameworks}
112}
fe0a4c48
EK
113\newglossaryentry{softwareObfuscation}
114{
115 name={software obfuscation},
116 description={makes source code harder to read and analyze, while preserving
117 its semantics}
118}
119\newglossaryentry{extractClass}
120{
121 name=\refa{Extract Class},
122 description={The \refa{Extract Class} refactoring works by creating a class,
123for then to move members from another class to that class and access them from
124the old class via a reference to the new class}
125}
126\newglossaryentry{designPattern}
127{
128 name={design pattern},
129 description={A design pattern is a named abstraction, that is meant to solve a
130 general design problem. It describes the key aspects of a common problem and
131identifies its participators and how they collaborate},
132 plural={design patterns}
133}
1c521a77
EK
134\newglossaryentry{enclosingClass}
135{
136 name={enclosing class},
137 description={An enclosing class is the class that surrounds any specific piece
138 of code that is written in the inner scope of this class},
139}
81cf9554
EK
140\newglossaryentry{mementoPattern}
141{
142 name={memento pattern},
143 description={The memento pattern is a software design pattern that is used to
144 capture an object's internal state so that it can be restored to this state
145 later\citing{designPatterns}},
146}
b4a197fd
EK
147%\newglossaryentry{extractMethod}
148%{
149% name=\refa{Extract Method},
150% description={The \refa{Extract Method} refactoring is used to extract a
151%fragment of code from its context and into a new method. A call to the new
152%method is inlined where the fragment was before. It is used to break code into
153%logical units, with names that explain their purpose}
154%}
155%\newglossaryentry{moveMethod}
156%{
157% name=\refa{Move Method},
158% description={The \refa{Move Method} refactoring is used to move a method from
159% one class to another. This is useful if the method is using more features of
160% another class than of the class which it is currently defined. Then all calls
161% to this method must be updated, or the method must be copied, with the old
162%method delegating to the new method}
163%}
f5fb40e4 164
7c28933b 165\bibliography{bibliography/master-thesis-erlenkr-bibliography}
6fabec9b
EK
166\DefineBibliographyStrings{english}{%
167 bibliography = {References},
168}
97ae6df1
EK
169\newbibmacro{string+doi}[1]{%
170 \iffieldundef{doi}{#1}{\href{http://dx.doi.org/\thefield{doi}}{#1}}}
171\DeclareFieldFormat{title}{\usebibmacro{string+doi}{\mkbibemph{#1}}}
172\DeclareFieldFormat[article]{title}{\usebibmacro{string+doi}{\mkbibquote{#1}}}
9ff90080 173
c8088eec
EK
174% UML comment in TikZ:
175% ref: https://tex.stackexchange.com/questions/103688/folded-paper-shape-tikz
43ca7be4
EK
176\makeatletter
177\pgfdeclareshape{umlcomment}{
178 \inheritsavedanchors[from=rectangle] % this is nearly a rectangle
179 \inheritanchorborder[from=rectangle]
180 \inheritanchor[from=rectangle]{center}
181 \inheritanchor[from=rectangle]{north}
182 \inheritanchor[from=rectangle]{south}
183 \inheritanchor[from=rectangle]{west}
184 \inheritanchor[from=rectangle]{east}
185 % ... and possibly more
186 \backgroundpath{% this is new
187 % store lower right in xa/ya and upper right in xb/yb
188 \southwest \pgf@xa=\pgf@x \pgf@ya=\pgf@y
189 \northeast \pgf@xb=\pgf@x \pgf@yb=\pgf@y
190 % compute corner of ‘‘flipped page’’
191 \pgf@xc=\pgf@xb \advance\pgf@xc by-10pt % this should be a parameter
192 \pgf@yc=\pgf@yb \advance\pgf@yc by-10pt
193 % construct main path
194 \pgfpathmoveto{\pgfpoint{\pgf@xa}{\pgf@ya}}
195 \pgfpathlineto{\pgfpoint{\pgf@xa}{\pgf@yb}}
196 \pgfpathlineto{\pgfpoint{\pgf@xc}{\pgf@yb}}
197 \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@yc}}
198 \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@ya}}
199 \pgfpathclose
200 % add little corner
201 \pgfpathmoveto{\pgfpoint{\pgf@xc}{\pgf@yb}}
202 \pgfpathlineto{\pgfpoint{\pgf@xc}{\pgf@yc}}
203 \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@yc}}
204 \pgfpathlineto{\pgfpoint{\pgf@xc}{\pgf@yc}}
205 }
206}
207\makeatother
208
209\tikzstyle{comment}=[%
210 draw,
211 drop shadow,
212 fill=white,
213 align=center,
214 shape=document,
215 minimum width=20mm,
216 minimum height=10mm,
217 shape=umlcomment,
218 inner sep=2ex,
219 font=\ttfamily,
220]
221
f5fb40e4
EK
222%\interfootnotelinepenalty=10000
223
c9488804
EK
224% Space between table rows
225\renewcommand{\arraystretch}{1.3}
6fabec9b 226% Multicolumns
bc7b5d67 227\newcommand{\spancols}[2]{\multicolumn{#1}{@{}l@{}}{#2}}
6fabec9b
EK
228% Column types
229\newcolumntype{L}[1]{>{\hsize=#1\hsize\raggedright\arraybackslash}X}%
230\newcolumntype{R}[1]{>{\hsize=#1\hsize\raggedleft\arraybackslash}X}%
c9488804 231
97ae6df1 232
9ff90080 233\begin{document}
0cbeeadb
EK
234%\pagenumbering{arabic}
235\mainmatter
531c4132 236\ififorside
0cbeeadb 237%\frontmatter{}
9ff90080 238
0cbeeadb 239%\setcounter{page}{3}
9ff90080
EK
240
241\chapter*{Abstract}
064227e3
EK
242\todoin{\textbf{Remove all todos (including list) before delivery/printing!!!
243Can be done by removing ``draft'' from documentclass.}}
889ba93e 244\todoin{Write abstract}
9ff90080
EK
245
246\tableofcontents{}
247\listoffigures{}
248\listoftables{}
97ae6df1 249\listoflistings{}
9ff90080 250
0cbeeadb
EK
251%\mainmatter
252%\setcounter{page}{13}
253
af21f437 254\chapter{Introduction}
97ae6df1 255
af21f437 256\section{Motivation and structure}
00aa0588 257
97ae6df1
EK
258For large software projects, complex program source code is an issue. It impacts
259the cost of maintenance in a negative way. It often stalls the implementation of
260new functionality and other program changes. The code may be difficult to
261understand, the changes may introduce new bugs that are hard to find and its
262complexity can simply keep people from doing code changes in fear of breaking
263some dependent piece of code. All these problems are related, and often lead to
264a vicious circle that slowly degrades the overall quality of a project.
265
266More specifically, and in an object-oriented context, a class may depend on a
267number of other classes. Sometimes these intimate relationships are appropriate,
268and sometimes they are not. Inappropriate \emph{coupling} between classes can
269make it difficult to know whether or not a change that is aimed at fixing a
270specific problem also alters the behavior of another part of a program.
271
272One of the tools that are used to fight complexity and coupling in program
273source code is \emph{refactoring}. The intention for this master's thesis is
274therefore to create an automated composite refactoring that reduces coupling
275between classes. The refactoring shall be able to operate automatically in all
276phases of a refactoring, from performing analysis to executing changes. It is
277also a requirement that it should be able to process large quantities of source
278code in a reasonable amount of time.
279
280
281\todoin{Structure. Write later\ldots}
282
283
b4d90424 284\section{What is refactoring?}
7c28933b 285
f3a108c3
EK
286This question is best answered by first defining the concept of a
287\emph{refactoring}, what it is to \emph{refactor}, and then discuss what aspects
a1bafe90 288of programming make people want to refactor their code.
00aa0588 289
b4d90424 290\subsection{Defining refactoring}
a1bafe90 291Martin Fowler, in his classic book on refactoring\citing{refactoring}, defines a
00aa0588 292refactoring like this:
ee45c41f 293
00aa0588 294\begin{quote}
aa1e3779
EK
295 \emph{Refactoring} (noun): a change made to the internal
296 structure\footnote{The structure observable by the programmer.} of software to
297 make it easier to understand and cheaper to modify without changing its
298 observable behavior.~\cite[p.~53]{refactoring}
00aa0588 299\end{quote}
ee45c41f 300
a1bafe90 301\noindent This definition assigns additional meaning to the word
ee45c41f
EK
302\emph{refactoring}, beyond the composition of the prefix \emph{re-}, usually
303meaning something like ``again'' or ``anew'', and the word \emph{factoring},
6c51af15
EK
304that can mean to isolate the \emph{factors} of something. Here a \emph{factor}
305would be close to the mathematical definition of something that divides a
306quantity, without leaving a remainder. Fowler is mixing the \emph{motivation}
a1bafe90
EK
307behind refactoring into his definition. Instead it could be more refined, formed
308to only consider the \emph{mechanical} and \emph{behavioral} aspects of
309refactoring. That is to factor the program again, putting it together in a
310different way than before, while preserving the behavior of the program. An
311alternative definition could then be:
6c51af15
EK
312
313\definition{A \emph{refactoring} is a transformation
8fae7b44 314done to a program without altering its external behavior.}
00aa0588 315
ee1d883a
EK
316From this we can conclude that a refactoring primarily changes how the
317\emph{code} of a program is perceived by the \emph{programmer}, and not the
740e1b6c
EK
318\emph{behavior} experienced by any user of the program. Although the logical
319meaning is preserved, such changes could potentially alter the program's
320behavior when it comes to performance gain or -penalties. So any logic depending
321on the performance of a program could make the program behave differently after
322a refactoring.
00aa0588 323
fe0a4c48
EK
324In the extreme case one could argue that \gloss{softwareObfuscation} is
325refactoring. It is often used to protect proprietary software. It restrains
326uninvited viewers, so they have a hard time analyzing code that they are not
327supposed to know how works. This could be a problem when using a language that
328is possible to decompile, such as Java.
b4e539f7
EK
329
330Obfuscation could be done composing many, more or less randomly chosen,
331refactorings. Then the question arises whether it can be called a
332\emph{composite refactoring} or not \see{compositeRefactorings}? The answer is
333not obvious. First, there is no way to describe the mechanics of software
334obfuscation, because there are infinitely many ways to do that. Second,
335obfuscation can be thought of as \emph{one operation}: Either the code is
336obfuscated, or it is not. Third, it makes no sense to call software obfuscation
337\emph{a refactoring}, since it holds different meaning to different people.
338
339This last point is important, since one of the motivations behind defining
340different refactorings, is to establish a \emph{vocabulary} for software
341professionals to use when reasoning about and discussing programs, similar to
fe0a4c48 342the motivation behind \glosspl{designPattern}\citing{designPatterns}.
b4e539f7
EK
343\begin{comment}
344So for describing \emph{software obfuscation}, it might be more appropriate to
345define what you do when performing it rather than precisely defining its
346mechanics in terms of other refactorings.
347\end{comment}
00aa0588 348
b4d90424 349\subsection{The etymology of 'refactoring'}
f3a108c3
EK
350It is a little difficult to pinpoint the exact origin of the word
351``refactoring'', as it seems to have evolved as part of a colloquial
352terminology, more than a scientific term. There is no authoritative source for a
353formal definition of it.
354
b5c7bb1b 355According to Martin Fowler\citing{etymology-refactoring}, there may also be more
f3a108c3 356than one origin of the word. The most well-known source, when it comes to the
b4e539f7
EK
357origin of \emph{refactoring}, is the
358Smalltalk\footnote{\label{footNote}Programming language} community and their
fe0a4c48 359infamous \name{Refactoring
f3a108c3 360Browser}\footnote{\url{http://st-www.cs.illinois.edu/users/brant/Refactory/RefactoringBrowser.html}}
fe0a4c48 361described in the article \tit{A Refactoring Tool for
b5c7bb1b
EK
362Smalltalk}\citing{refactoringBrowser1997}, published in 1997.
363Allegedly\citing{etymology-refactoring}, the metaphor of factoring programs was
b4e539f7 364also present in the Forth\textsuperscript{\ref{footNote}} community, and the
fe0a4c48
EK
365word ``refactoring'' is mentioned in a book by Leo Brodie, called \tit{Thinking
366Forth}\citing{brodie2004}, first published in 1984\footnote{\tit{Thinking Forth}
367was first published in 1984 by the \name{Forth Interest Group}. Then it was
368reprinted in 1994 with minor typographical corrections, before it was
b4e539f7
EK
369transcribed into an electronic edition typeset in \LaTeX\ and published under a
370Creative Commons licence in
3712004. The edition cited here is the 2004 edition, but the content should
372essentially be as in 1984.}. The exact word is only printed one
373place~\cite[p.~232]{brodie2004}, but the term \emph{factoring} is prominent in
374the book, that also contains a whole chapter dedicated to (re)factoring, and how
375to keep the (Forth) code clean and maintainable.
ee45c41f 376
f3a108c3
EK
377\begin{quote}
378 \ldots good factoring technique is perhaps the most important skill for a
3a154bb7 379 Forth programmer.~\cite[p.~172]{brodie2004}
f3a108c3 380\end{quote}
ee45c41f
EK
381
382\noindent Brodie also express what \emph{factoring} means to him:
383
f3a108c3
EK
384\begin{quote}
385 Factoring means organizing code into useful fragments. To make a fragment
386 useful, you often must separate reusable parts from non-reusable parts. The
387 reusable parts become new definitions. The non-reusable parts become arguments
3a154bb7 388 or parameters to the definitions.~\cite[p.~172]{brodie2004}
f3a108c3
EK
389\end{quote}
390
391Fowler claims that the usage of the word \emph{refactoring} did not pass between
fe0a4c48 392the \name{Forth} and \name{Smalltalk} communities, but that it emerged
f3a108c3
EK
393independently in each of the communities.
394
b4d90424 395\subsection{Reasons for refactoring}
2f6e6dec
EK
396There are many reasons why people want to refactor their programs. They can for
397instance do it to remove duplication, break up long methods or to introduce
b4e539f7
EK
398design patterns into their software systems. The shared trait for all these are
399that peoples' intentions are to make their programs \emph{better}, in some
400sense. But what aspects of their programs are becoming improved?
401
402As just mentioned, people often refactor to get rid of duplication. They are
403moving identical or similar code into methods, and are pushing methods up or
404down in their class hierarchies. They are making template methods for
405overlapping algorithms/functionality, and so on. It is all about gathering what
406belongs together and putting it all in one place. The resulting code is then
407easier to maintain. When removing the implicit coupling\footnote{When
408 duplicating code, the duplicate pieces of code might not be coupled, apart
409from representing the same functionality. So if this functionality is going to
410change, it might need to change in more than one place, thus creating an
411implicit coupling between multiple pieces of code.} between code snippets, the
137e0e7b 412location of a bug is limited to only one place, and new functionality need only
a1bafe90
EK
413to be added to this one place, instead of a number of places people might not
414even remember.
415
416A problem you often encounter when programming, is that a program contains a lot
417of long and hard-to-grasp methods. It can then help to break the methods into
b4a197fd
EK
418smaller ones, using the \ExtractMethod refactoring\citing{refactoring}. Then
419you may discover something about a program that you were not aware of before;
420revealing bugs you did not know about or could not find due to the complex
078b1e4a
EK
421structure of your program. Making the methods smaller and giving good names to
422the new ones clarifies the algorithms and enhances the \emph{understandability}
423of the program \see{magic_number_seven}. This makes refactoring an excellent
424method for exploring unknown program code, or code that you had forgotten that
425you wrote.
a1bafe90 426
b4e539f7
EK
427Most primitive refactorings are simple, and usually involves moving code
428around\citing{kerievsky2005}. The motivation behind them may first be revealed
429when they are combined into larger --- higher level --- refactorings, called
a1bafe90 430\emph{composite refactorings} \see{compositeRefactorings}. Often the goal of
b4e539f7
EK
431such a series of refactorings is a design pattern. Thus the design can
432\emph{evolve} throughout the lifetime of a program, as opposed to designing
433up-front. It is all about being structured and taking small steps to improve a
434program's design.
a1bafe90
EK
435
436Many software design pattern are aimed at lowering the coupling between
437different classes and different layers of logic. One of the most famous is
fe0a4c48
EK
438perhaps the \pattern{Model-View-Controller}\citing{designPatterns} pattern. It
439is aimed at lowering the coupling between the user interface, the business logic
b4e539f7
EK
440and the data representation of a program. This also has the added benefit that
441the business logic could much easier be the target of automated tests, thus
442increasing the productivity in the software development process.
0b0567f2
EK
443
444Another effect of refactoring is that with the increased separation of concerns
a1bafe90
EK
445coming out of many refactorings, the \emph{performance} can be improved. When
446profiling programs, the problematic parts are narrowed down to smaller parts of
447the code, which are easier to tune, and optimization can be performed only where
b4e539f7 448needed and in a more effective way\citing{refactoring}.
137e0e7b 449
b01d328a
EK
450Last, but not least, and this should probably be the best reason to refactor, is
451to refactor to \emph{facilitate a program change}. If one has managed to keep
452one's code clean and tidy, and the code is not bloated with design patterns that
a1bafe90 453are not ever going to be needed, then some refactoring might be needed to
b01d328a
EK
454introduce a design pattern that is appropriate for the change that is going to
455happen.
456
137e0e7b
EK
457Refactoring program code --- with a goal in mind --- can give the code itself
458more value. That is in the form of robustness to bugs, understandability and
a1bafe90
EK
459maintainability. Having robust code is an obvious advantage, but
460understandability and maintainability are both very important aspects of
461software development. By incorporating refactoring in the development process,
462bugs are found faster, new functionality is added more easily and code is easier
463to understand by the next person exposed to it, which might as well be the
464person who wrote it. The consequence of this, is that refactoring can increase
465the average productivity of the development process, and thus also add to the
466monetary value of a business in the long run. The perspective on productivity
467and money should also be able to open the eyes of the many nearsighted managers
468that seldom see beyond the next milestone.
137e0e7b 469
b4d90424 470\subsection{The magical number seven}\label{magic_number_seven}
fe0a4c48
EK
471The article \tit{The magical number seven, plus or minus two: some limits on our
472capacity for processing information}\citing{miller1956} by George A. Miller,
473was published in the journal \name{Psychological Review} in 1956. It presents
474evidence that support that the capacity of the number of objects a human being
475can hold in its working memory is roughly seven, plus or minus two objects. This
476number varies a bit depending on the nature and complexity of the objects, but
477is according to Miller ``\ldots never changing so much as to be
f4cea2d6
EK
478unrecognizable.''
479
480Miller's article culminates in the section called \emph{Recoding}, a term he
481borrows from communication theory. The central result in this section is that by
482recoding information, the capacity of the amount of information that a human can
483process at a time is increased. By \emph{recoding}, Miller means to group
b4e539f7
EK
484objects together in chunks, and give each chunk a new name that it can be
485remembered by.
f4cea2d6
EK
486
487\begin{quote}
488 \ldots recoding is an extremely powerful weapon for increasing the amount of
4cb06723 489 information that we can deal with.~\cite[p.~95]{miller1956}
f4cea2d6 490\end{quote}
ee45c41f 491
b4e539f7
EK
492By organizing objects into patterns of ever growing depth, one can memorize and
493process a much larger amount of data than if it were to be represented as its
494basic pieces. This grouping and renaming is analogous to how many refactorings
495work, by grouping pieces of code and give them a new name. Examples are the
fe0a4c48 496fundamental \ExtractMethod and \refa{Extract Class}
b4e539f7
EK
497refactorings\citing{refactoring}.
498
a1bafe90 499An example from the article addresses the problem of memorizing a sequence of
b4e539f7
EK
500binary digits. The example presented here is a slightly modified version of the
501one presented in the original article\citing{miller1956}, but it preserves the
3ab3e132 502essence of it. Let us say we have the following sequence of
f4cea2d6
EK
50316 binary digits: ``1010001001110011''. Most of us will have a hard time
504memorizing this sequence by only reading it once or twice. Imagine if we instead
505translate it to this sequence: ``A273''. If you have a background from computer
b4e539f7
EK
506science, it will be obvious that the latter sequence is the first sequence
507recoded to be represented by digits in base 16. Most people should be able to
f4cea2d6
EK
508memorize this last sequence by only looking at it once.
509
510Another result from the Miller article is that when the amount of information a
511human must interpret increases, it is crucial that the translation from one code
512to another must be almost automatic for the subject to be able to remember the
0d7fbd88 513translation, before \heshe is presented with new information to recode. Thus
f4cea2d6
EK
514learning and understanding how to best organize certain kinds of data is
515essential to efficiently handle that kind of data in the future. This is much
a1bafe90
EK
516like when humans learn to read. First they must learn how to recognize letters.
517Then they can learn distinct words, and later read sequences of words that form
518whole sentences. Eventually, most of them will be able to read whole books and
519briefly retell the important parts of its content. This suggest that the use of
b4e539f7
EK
520design patterns is a good idea when reasoning about computer programs. With
521extensive use of design patterns when creating complex program structures, one
522does not always have to read whole classes of code to comprehend how they
523function, it may be sufficient to only see the name of a class to almost fully
524understand its responsibilities.
f4cea2d6
EK
525
526\begin{quote}
527 Our language is tremendously useful for repackaging material into a few chunks
4cb06723 528 rich in information.~\cite[p.~95]{miller1956}
f4cea2d6 529\end{quote}
ee45c41f 530
a1bafe90 531Without further evidence, these results at least indicate that refactoring
f4cea2d6
EK
532source code into smaller units with higher cohesion and, when needed,
533introducing appropriate design patterns, should aid in the cause of creating
b4e539f7 534computer programs that are easier to maintain and have code that is easier (and
f4cea2d6
EK
535better) understood.
536
b4d90424 537\subsection{Notable contributions to the refactoring literature}
36d99783 538
d21ef41f
EK
539\begin{description}
540 \item[1992] William F. Opdyke submits his doctoral dissertation called
fe0a4c48
EK
541 \tit{Refactoring Object-Oriented Frameworks}\citing{opdyke1992}. This work
542 defines a set of refactorings, that are behavior preserving given that their
543 preconditions are met. The dissertation is focused on the automation of
544 refactorings.
545 \item[1999] Martin Fowler et al.: \tit{Refactoring: Improving the Design of
b5c7bb1b
EK
546 Existing Code}\citing{refactoring}. This is maybe the most influential text
547 on refactoring. It bares similarities with Opdykes thesis\citing{opdyke1992}
d21ef41f
EK
548 in the way that it provides a catalog of refactorings. But Fowler's book is
549 more about the craft of refactoring, as he focuses on establishing a
550 vocabulary for refactoring, together with the mechanics of different
551 refactorings and when to perform them. His methodology is also founded on
fe0a4c48
EK
552 the principles of test-driven development.
553 \item[2005] Joshua Kerievsky: \tit{Refactoring to
36d99783 554 Patterns}\citing{kerievsky2005}. This book is heavily influenced by Fowler's
fe0a4c48 555 \tit{Refactoring}\citing{refactoring} and the ``Gang of Four'' \tit{Design
36d99783
EK
556 Patterns}\citing{designPatterns}. It is building on the refactoring
557 catalogue from Fowler's book, but is trying to bridge the gap between
558 \emph{refactoring} and \emph{design patterns} by providing a series of
559 higher-level composite refactorings, that makes code evolve toward or away
fe0a4c48 560 from certain design patterns. The book is trying to build up the reader's
36d99783
EK
561 intuition around \emph{why} one would want to use a particular design
562 pattern, and not just \emph{how}. The book is encouraging evolutionary
e123ab03 563 design \see{relationToDesignPatterns}.
d21ef41f 564\end{description}
3b7c1d90 565
b4d90424 566\subsection{Tool support (for Java)}\label{toolSupport}
3ab3e132 567This section will briefly compare the refactoring support of the three IDEs
fe0a4c48
EK
568\name{Eclipse}\footnote{\url{http://www.eclipse.org/}}, \name{IntelliJ
569IDEA}\footnote{The IDE under comparison is the \name{Community Edition},
4e135659 570\url{http://www.jetbrains.com/idea/}} and
fe0a4c48 571\name{NetBeans}\footnote{\url{https://netbeans.org/}}. These are the most
4e135659
EK
572popular Java IDEs\citing{javaReport2011}.
573
574All three IDEs provide support for the most useful refactorings, like the
575different extract, move and rename refactorings. In fact, Java-targeted IDEs are
576known for their good refactoring support, so this did not appear as a big
577surprise.
578
579The IDEs seem to have excellent support for the \ExtractMethod refactoring, so
b4e539f7
EK
580at least they have all passed the first ``refactoring
581rubicon''\citing{fowlerRubicon2001,secondRubicon2012}.
4e135659 582
b4a197fd
EK
583Regarding the \MoveMethod refactoring, the \name{Eclipse} and \name{IntelliJ}
584IDEs do the job in very similar manners. In most situations they both do a
585satisfying job by producing the expected outcome. But they do nothing to check
586that the result does not break the semantics of the program \see{correctness}.
fe0a4c48 587The \name{NetBeans} IDE implements this refactoring in a somewhat
b4e539f7
EK
588unsophisticated way. For starters, the refactoring's default destination for the
589move, is the same class as the method already resides in, although it refuses to
590perform the refactoring if chosen. But the worst part is, that if moving the
591method \method{f} of the class \type{C} to the class \type{X}, it will break the
592code. The result is shown in \myref{lst:moveMethod_NetBeans}.
4e135659 593
347ed677
EK
594\begin{listing}
595\begin{multicols}{2}
4e135659
EK
596\begin{minted}[samepage]{java}
597public class C {
598 private X x;
599 ...
600 public void f() {
601 x.m();
602 x.n();
603 }
604}
605\end{minted}
606
347ed677 607\columnbreak
4e135659
EK
608
609\begin{minted}[samepage]{java}
610public class X {
611 ...
612 public void f(C c) {
613 c.x.m();
614 c.x.n();
615 }
616}
617\end{minted}
347ed677
EK
618\end{multicols}
619\caption{Moving method \method{f} from \type{C} to \type{X}.}
620\label{lst:moveMethod_NetBeans}
621\end{listing}
4e135659 622
fe0a4c48 623\name{NetBeans} will try to create code that call the methods \method{m} and \method{n}
4e135659 624of \type{X} by accessing them through \var{c.x}, where \var{c} is a parameter of
a1bafe90
EK
625type \type{C} that is added the method \method{f} when it is moved. (This is
626seldom the desired outcome of this refactoring, but ironically, this ``feature''
fe0a4c48 627keeps \name{NetBeans} from breaking the code in the example from \myref{correctness}.)
8b6b22c8 628If \var{c.x} for some reason is inaccessible to \type{X}, as in this case, the
fe0a4c48 629refactoring breaks the code, and it will not compile. \name{NetBeans} presents a
8b6b22c8
EK
630preview of the refactoring outcome, but the preview does not catch it if the IDE
631is about break the program.
4778044b 632
b4e539f7 633The IDEs under investigation seem to have fairly good support for primitive
fe0a4c48
EK
634refactorings, but what about more complex ones, such as
635\gloss{extractClass}\citing{refactoring}? \name{IntelliJ} handles this in a
636fairly good manner, although, in the case of private methods, it leaves unused
a1bafe90 637methods behind. These are methods that delegate to a field with the type of the
fe0a4c48
EK
638new class, but are not used anywhere. \name{Eclipse} has added its own quirk to
639the \refa{Extract Class} refactoring, and only allows for \emph{fields} to be
640moved to a new class, \emph{not methods}. This makes it effectively only
641extracting a data structure, and calling it \refa{Extract Class} is a little
b4e539f7 642misleading. One would often be better off with textual extract and paste than
fe0a4c48
EK
643using the \refa{Extract Class} refactoring in \name{Eclipse}. When it comes to
644\name{NetBeans}, it does not even show an attempt on providing this refactoring.
4778044b 645
b4d90424 646\subsection{The relation to design patterns}\label{relationToDesignPatterns}
4cb06723 647
fe0a4c48
EK
648Refactoring and design patterns have at least one thing in common, they are both
649promoted by advocates of \emph{clean code}\citing{cleanCode} as fundamental
650tools on the road to more maintainable and extendable source code.
4cb06723
EK
651
652\begin{quote}
653 Design patterns help you determine how to reorganize a design, and they can
654 reduce the amount of refactoring you need to do
655 later.~\cite[p.~353]{designPatterns}
656\end{quote}
657
a1bafe90
EK
658Although sometimes associated with
659over-engineering\citing{kerievsky2005,refactoring}, design patterns are in
660general assumed to be good for maintainability of source code. That may be
d1adbeef
EK
661because many of them are designed to support the \emph{open/closed principle} of
662object-oriented programming. The principle was first formulated by Bertrand
663Meyer, the creator of the Eiffel programming language, like this: ``Modules
664should be both open and closed.''\citing{meyer1988} It has been popularized,
665with this as a common version:
666
667\begin{quote}
668 Software entities (classes, modules, functions, etc.) should be open for
669 extension, but closed for modification.\footnote{See
670 \url{http://c2.com/cgi/wiki?OpenClosedPrinciple} or
671 \url{https://en.wikipedia.org/wiki/Open/closed_principle}}
672\end{quote}
673
674Maintainability is often thought of as the ability to be able to introduce new
a1bafe90 675functionality without having to change too much of the old code. When
d1adbeef
EK
676refactoring, the motivation is often to facilitate adding new functionality. It
677is about factoring the old code in a way that makes the new functionality being
678able to benefit from the functionality already residing in a software system,
679without having to copy old code into new. Then, next time someone shall add new
a1bafe90
EK
680functionality, it is less likely that the old code has to change. Assuming that
681a design pattern is the best way to get rid of duplication and assist in
682implementing new functionality, it is reasonable to conclude that a design
683pattern often is the target of a series of refactorings. Having a repertoire of
684design patterns can also help in knowing when and how to refactor a program to
685make it reflect certain desired characteristics.
d1adbeef
EK
686
687\begin{quote}
a1bafe90 688 There is a natural relation between patterns and refactorings. Patterns are
d1adbeef
EK
689 where you want to be; refactorings are ways to get there from somewhere
690 else.~\cite[p.~107]{refactoring}
691\end{quote}
692
693This quote is wise in many contexts, but it is not always appropriate to say
a1bafe90
EK
694``Patterns are where you want to be\ldots''. \emph{Sometimes}, patterns are
695where you want to be, but only because it will benefit your design. It is not
696true that one should always try to incorporate as many design patterns as
697possible into a program. It is not like they have intrinsic value. They only add
698value to a system when they support its design. Otherwise, the use of design
699patterns may only lead to a program that is more complex than necessary.
d1adbeef
EK
700
701\begin{quote}
702 The overuse of patterns tends to result from being patterns happy. We are
703 \emph{patterns happy} when we become so enamored of patterns that we simply
704 must use them in our code.~\cite[p.~24]{kerievsky2005}
705\end{quote}
706
707This can easily happen when relying largely on up-front design. Then it is
708natural, in the very beginning, to try to build in all the flexibility that one
709believes will be necessary throughout the lifetime of a software system.
710According to Joshua Kerievsky ``That sounds reasonable --- if you happen to be
711psychic.''~\cite[p.~1]{kerievsky2005} He is advocating what he believes is a
712better approach: To let software continually evolve. To start with a simple
713design that meets today's needs, and tackle future needs by refactoring to
714satisfy them. He believes that this is a more economic approach than investing
715time and money into a design that inevitably is going to change. By relying on
716continuously refactoring a system, its design can be made simpler without
717sacrificing flexibility. To be able to fully rely on this approach, it is of
e123ab03 718utter importance to have a reliable suit of tests to lean on \see{testing}. This
d1adbeef
EK
719makes the design process more natural and less characterized by difficult
720decisions that has to be made before proceeding in the process, and that is
721going to define a project for all of its unforeseeable future.
722
b4d90424 723\subsection{The impact on software quality}
00aa0588 724
b4d90424 725\subsubsection{What is software quality?}
00aa0588 726The term \emph{software quality} has many meanings. It all depends on the
9a55a5bc 727context we put it in. If we look at it with the eyes of a software developer, it
a1bafe90 728usually means that the software is easily maintainable and testable, or in other
9a55a5bc
EK
729words, that it is \emph{well designed}. This often correlates with the
730management scale, where \emph{keeping the schedule} and \emph{customer
137e0e7b
EK
731satisfaction} is at the center. From the customers point of view, in addition to
732good usability, \emph{performance} and \emph{lack of bugs} is always
733appreciated, measurements that are also shared by the software developer. (In
734addition, such things as good documentation could be measured, but this is out
735of the scope of this document.)
9a55a5bc 736
b4d90424 737\subsubsection{The impact on performance}
9a55a5bc 738\begin{quote}
a1bafe90
EK
739 Refactoring certainly will make software go more slowly\footnote{With todays
740 compiler optimization techniques and performance tuning of e.g. the Java
741virtual machine, the penalties of object creation and method calls are
742debatable.}, but it also makes the software more amenable to performance
743tuning.~\cite[p.~69]{refactoring}
9a55a5bc 744\end{quote}
ee45c41f
EK
745
746\noindent There is a common belief that refactoring compromises performance, due
747to increased degree of indirection and that polymorphism is slower than
9a55a5bc
EK
748conditionals.
749
b5c7bb1b 750In a survey, Demeyer\citing{demeyer2002} disproves this view in the case of
a1bafe90 751polymorphism. He did an experiment on, what he calls, ``Transform Self Type
9a55a5bc
EK
752Checks'' where you introduce a new polymorphic method and a new class hierarchy
753to get rid of a class' type checking of a ``type attribute``. He uses this kind
754of transformation to represent other ways of replacing conditionals with
755polymorphism as well. The experiment is performed on the C++ programming
a1bafe90
EK
756language and with three different compilers and platforms. Demeyer concludes
757that, with compiler optimization turned on, polymorphism beats middle to large
758sized if-statements and does as well as case-statements. (In accordance with
759his hypothesis, due to similarities between the way C++ handles polymorphism and
760case-statements.)
ee45c41f 761
9a55a5bc
EK
762\begin{quote}
763 The interesting thing about performance is that if you analyze most programs,
b5c7bb1b 764 you find that they waste most of their time in a small fraction of the
4cb06723 765 code.~\cite[p.~70]{refactoring}
9a55a5bc 766\end{quote}
9a55a5bc 767
ee45c41f
EK
768\noindent So, although an increased amount of method calls could potentially
769slow down programs, one should avoid premature optimization and sacrificing good
fe0a4c48
EK
770design, leaving the performance tuning until after \gloss{profiling} the
771software and having isolated the actual problem areas.
00aa0588 772
b4d90424 773\subsection{Composite refactorings}\label{compositeRefactorings}
6065c96c 774Generally, when thinking about refactoring, at the mechanical level, there are
f65da046 775essentially two kinds of refactorings. There are the \emph{primitive}
a1bafe90 776refactorings, and the \emph{composite} refactorings.
6065c96c 777
6c51af15
EK
778\definition{A \emph{primitive refactoring} is a refactoring that cannot be
779expressed in terms of other refactorings.}
f65da046 780
fe0a4c48 781\noindent Examples are the \refa{Pull Up Field} and \refa{Pull Up
a1bafe90 782Method} refactorings\citing{refactoring}, that move members up in their class
ee45c41f
EK
783hierarchies.
784
6c51af15
EK
785\definition{A \emph{composite refactoring} is a refactoring that can be
786expressed in terms of two or more other refactorings.}
f65da046 787
fe0a4c48 788\noindent An example of a composite refactoring is the \refa{Extract
b5c7bb1b
EK
789Superclass} refactoring\citing{refactoring}. In its simplest form, it is composed
790of the previously described primitive refactorings, in addition to the
fe0a4c48 791\refa{Pull Up Constructor Body} refactoring\citing{refactoring}. It works
b5c7bb1b 792by creating an abstract superclass that the target class(es) inherits from, then
fe0a4c48
EK
793by applying \refa{Pull Up Field}, \refa{Pull Up Method} and
794\refa{Pull Up Constructor Body} on the members that are to be members of
f5fb40e4
EK
795the new superclass. If there are multiple classes in play, their interfaces may
796need to be united with the help of some rename refactorings, before extracting
fe0a4c48 797the superclass. For an overview of the \refa{Extract Superclass}
8b6b22c8 798refactoring, see \myref{fig:extractSuperclass}.
6065c96c 799
ddcea0b5
EK
800\begin{figure}[h]
801 \centering
faa9f4f3 802 \includegraphics[angle=270,width=\linewidth]{extractSuperclassItalic.pdf}
f5fb40e4 803 \caption{The Extract Superclass refactoring, with united interfaces.}
ddcea0b5
EK
804 \label{fig:extractSuperclass}
805\end{figure}
6065c96c 806
b4d90424 807\subsection{Manual vs. automated refactorings}
0d7fbd88 808Refactoring is something every programmer does, even if \heshe does not known
f65da046
EK
809the term \emph{refactoring}. Every refinement of source code that does not alter
810the program's behavior is a refactoring. For small refactorings, such as
0d7fbd88 811\ExtractMethod, executing it manually is a manageable task, but is still prone
a1bafe90 812to errors. Getting it right the first time is not easy, considering the method
f65da046
EK
813signature and all the other aspects of the refactoring that has to be in place.
814
f5fb40e4
EK
815Consider the renaming of classes, methods and fields. For complex programs these
816refactorings are almost impossible to get right. Attacking them with textual
817search and replace, or even regular expressions, will fall short on these tasks.
818Then it is crucial to have proper tool support that can perform them
819automatically. Tools that can parse source code and thus have semantic knowledge
820about which occurrences of which names belong to what construct in the program.
821For even trying to perform one of these complex task manually, one would have to
822be very confident on the existing test suite \see{testing}.
00aa0588 823
b4d90424 824\subsection{Correctness of refactorings}\label{correctness}
f65da046 825For automated refactorings to be truly useful, they must show a high degree of
f5fb40e4
EK
826behavior preservation. This last sentence might seem obvious, but there are
827examples of refactorings in existing tools that break programs. In an ideal
828world, every automated refactoring would be ``complete'', in the sense that it
829would never break a program. In an ideal world, every program would also be free
830from bugs. In modern IDEs the implemented automated refactorings are working for
831\emph{most} cases, that is enough for making them useful.
832
833I will now present an example of a \emph{corner case} where a program breaks
834when a refactoring is applied. The example shows an \ExtractMethod refactoring
835followed by a \MoveMethod refactoring that breaks a program in both the
fe0a4c48 836\name{Eclipse} and \name{IntelliJ} IDEs\footnote{The \name{NetBeans} IDE handles this
3ab3e132 837 particular situation without altering the program's behavior, mainly because
fe0a4c48 838 its \refa{Move Method} refactoring implementation is a bit flawed in other ways
f5fb40e4
EK
839 \see{toolSupport}.}. The target and the destination for the composed
840 refactoring is shown in \myref{lst:correctnessExtractAndMove}. Note that the
841 method \method{m(C c)} of class \type{X} assigns to the field \var{x} of the
842 argument \var{c} that has type \type{C}.
843
844\begin{listing}[h]
845\begin{multicols}{2}
53be7239
EK
846\begin{minted}[linenos,frame=topline,label={Refactoring
847 target},framesep=\mintedframesep]{java}
ddcea0b5 848public class C {
f5fb40e4 849 public X x = new X();
ee45c41f 850
f5fb40e4
EK
851 public void f() {
852 x.m(this);
853 // Not the same x
854 x.n();
855 }
ddcea0b5
EK
856}
857\end{minted}
ee45c41f 858
f5fb40e4 859\columnbreak
ee45c41f 860
53be7239
EK
861\begin{minted}[frame=topline,label={Method
862 destination},framesep=\mintedframesep]{java}
ee45c41f 863public class X {
f5fb40e4
EK
864 public void m(C c) {
865 c.x = new X();
866 // If m is called from
867 // c, then c.x no longer
868 // equals 'this'
869 }
870 public void n() {}
ee45c41f
EK
871}
872\end{minted}
f5fb40e4
EK
873\end{multicols}
874\caption{The target and the destination for the composition of the Extract
fe0a4c48 875Method and \refa{Move Method} refactorings.}
f5fb40e4
EK
876\label{lst:correctnessExtractAndMove}
877\end{listing}
ee45c41f 878
f5fb40e4
EK
879
880The refactoring sequence works by extracting line 6 through 8 from the original
3510e539 881class \type{C} into a method \method{f} with the statements from those lines as
f5fb40e4
EK
882its method body (but with the comment left out, since it will no longer hold any
883meaning). The method is then moved to the class \type{X}. The result is shown
884in \myref{lst:correctnessExtractAndMoveResult}.
ee45c41f 885
f5fb40e4
EK
886Before the refactoring, the methods \method{m} and \method{n} of class \type{X}
887are called on different object instances (see line 6 and 8 of the original class
888\type{C} in \cref{lst:correctnessExtractAndMove}). After the refactoring, they
889are called on the same object, and the statement on line
8903 of class \type{X} (in \cref{lst:correctnessExtractAndMoveResult}) no longer
891 has the desired effect in our example. The method \method{f} of class \type{C}
892 is now calling the method \method{f} of class \type{X} (see line 5 of class
893 \type{C} in \cref{lst:correctnessExtractAndMoveResult}), and the program now
894 behaves different than before.
895
896\begin{listing}[h]
897\begin{multicols}{2}
898\begin{minted}[linenos]{java}
ee45c41f
EK
899public class C {
900 public X x = new X();
901
902 public void f() {
903 x.f(this);
904 }
905}
906\end{minted}
907
f5fb40e4
EK
908\columnbreak
909
910\begin{minted}[linenos]{java}
ee45c41f
EK
911public class X {
912 public void m(C c) {
913 c.x = new X();
914 }
915 public void n() {}
f5fb40e4
EK
916 // Extracted and
917 // moved method
ee45c41f
EK
918 public void f(C c) {
919 m(c);
920 n();
921 }
922}
923\end{minted}
f5fb40e4
EK
924\end{multicols}
925\caption{The result of the composed refactoring.}
926\label{lst:correctnessExtractAndMoveResult}
927\end{listing}
ddcea0b5 928
aa1e3779
EK
929The bug introduced in the previous example is of such a nature\footnote{Caused
930 by aliasing. See \url{https://en.wikipedia.org/wiki/Aliasing_(computing)}}
931 that it is very difficult to spot if the refactored code is not covered by
932 tests. It does not generate compilation errors, and will thus only result in
933 a runtime error or corrupted data, which might be hard to detect.
19c4f27d 934
b4d90424 935\subsection{Refactoring and the importance of testing}\label{testing}
19c4f27d
EK
936\begin{quote}
937 If you want to refactor, the essential precondition is having solid
938 tests.\citing{refactoring}
939\end{quote}
940
29f39f29
EK
941When refactoring, there are roughly three classes of errors that can be made.
942The first class of errors are the ones that make the code unable to compile.
943These \emph{compile-time} errors are of the nicer kind. They flash up at the
944moment they are made (at least when using an IDE), and are usually easy to fix.
945The second class are the \emph{runtime} errors. Although they take a bit longer
946to surface, they usually manifest after some time in an illegal argument
947exception, null pointer exception or similar during the program execution.
948These kind of errors are a bit harder to handle, but at least they will show,
949eventually. Then there are the \emph{behavior-changing} errors. These errors are
950of the worst kind. They do not show up during compilation and they do not turn
951on a blinking red light during runtime either. The program can seem to work
952perfectly fine with them in play, but the business logic can be damaged in ways
953that will only show up over time.
954
955For discovering runtime errors and behavior changes when refactoring, it is
956essential to have good test coverage. Testing in this context means writing
957automated tests. Manual testing may have its uses, but when refactoring, it is
958automated unit testing that dominate. For discovering behavior changes it is
959especially important to have tests that cover potential problems, since these
960kind of errors does not reveal themselves.
961
962Unit testing is not a way to \emph{prove} that a program is correct, but it is a
3ab3e132 963way to make you confident that it \emph{probably} works as desired. In the
4928aa0b 964context of test-driven development (commonly known as TDD), the tests are even a
29f39f29
EK
965way to define how the program is \emph{supposed} to work. It is then, by
966definition, working if the tests are passing.
19c4f27d
EK
967
968If the test coverage for a code base is perfect, then it should, theoretically,
29f39f29
EK
969be risk-free to perform refactorings on it. This is why automated tests and
970refactoring are such a great match.
f65da046 971
b4d90424 972\subsubsection{Testing the code from correctness section}
29f39f29
EK
973The worst thing that can happen when refactoring is to introduce changes to the
974behavior of a program, as in the example on \myref{correctness}. This example
975may be trivial, but the essence is clear. The only problem with the example is
976that it is not clear how to create automated tests for it, without changing it
977in intrusive ways.
978
20bcc7bf 979Unit tests, as they are known from the different \glosspl{xUnit} around, are
29f39f29
EK
980only suitable to test the \emph{result} of isolated operations. They can not
981easily (if at all) observe the \emph{history} of a program.
b5d53f51 982
a13e5650 983This problem is still open.
116805bf 984
a13e5650 985\begin{comment}
116805bf
EK
986
987Assuming a sequential (non-concurrent) program:
988
989\begin{minted}{java}
990tracematch (C c, X x) {
991 sym m before:
992 call(* X.m(C)) && args(c) && cflow(within(C));
993 sym n before:
994 call(* X.n()) && target(x) && cflow(within(C));
995 sym setCx after:
996 set(C.x) && target(c) && !cflow(m);
997
998 m n
999
1000 { assert x == c.x; }
1001}
1002\end{minted}
1003
1004%\begin{minted}{java}
1005%tracematch (X x1, X x2) {
1006% sym m before:
1007% call(* X.m(C)) && target(x1);
1008% sym n before:
1009% call(* X.n()) && target(x2);
1010% sym setX after:
1011% set(C.x) && !cflow(m) && !cflow(n);
1012%
1013% m n
1014%
1015% { assert x1 != x2; }
1016%}
1017%\end{minted}
a13e5650 1018\end{comment}
116805bf 1019
222d172b 1020
b4d90424 1021\section{The Project}
97ae6df1
EK
1022In this section we look at the work that shall be done for this project, its
1023building stones and some of the methodologies used.
222d172b 1024
b4d90424 1025\subsection{Project description}
60065669 1026The aim of this master's project will be to explore the relationship between the
0fe1a611
EK
1027\ExtractMethod and the \MoveMethod refactorings. This will be done by composing
1028the two into a composite refactoring. The refactoring will be called the
6a779665
EK
1029\ExtractAndMoveMethod refactoring.
1030
1031The two primitive \ExtractMethod and \MoveMethod refactorings must already be
1032implemented in a tool, so the \ExtractAndMoveMethod refactoring is going to be
1033built on top of those.
b5d53f51 1034
a13e5650
EK
1035The composition of the \ExtractMethod and \MoveMethod refactorings springs
1036naturally out of the need to move procedures closer to the data they manipulate.
1037This composed refactoring is not well described in the literature, but it is
1038implemented in at least one tool called
fe0a4c48
EK
1039\name{CodeRush}\footnote{\url{https://help.devexpress.com/\#CodeRush/CustomDocument3519}},
1040that is an extension for \name{MS Visual
b5d53f51 1041Studio}\footnote{\url{http://www.visualstudio.com/}}. In CodeRush it is called
fe0a4c48 1042\refa{Extract Method to
b5d53f51 1043Type}\footnote{\url{https://help.devexpress.com/\#CodeRush/CustomDocument6710}},
0e6e57d3 1044but I choose to call it \ExtractAndMoveMethod, since I feel this better
b5d53f51
EK
1045communicates which primitive refactorings it is composed of.
1046
0fe1a611 1047The project will consist of implementing the \ExtractAndMoveMethod refactoring,
0e6e57d3 1048as well as executing it over a larger code base, as a case study. To be able to
0fe1a611 1049execute the refactoring automatically, I have to make it analyze code to
0e6e57d3 1050determine the best selections to extract into new methods.
70905ddc 1051
97ae6df1
EK
1052\subsection{The premises}
1053Before we can start manipulating source code and write a tool for doing so, we
1054need to decide on a programming language for the code we are going to
1055manipulate. Also, since we do not want to start from scratch by implementing
1056primitive refactorings ourselves, we need to choose an existing tool that
1057provides the needed refactorings. In addition to be able to perform changes, we
1058need a framework for analyzing source code for the language we select.
1059
1060\subsubsection{Choosing the target language}
1061Choosing which programming language the code that shall be manipulated shall be
1062written in, is not a very difficult task. We choose to limit the possible
1063languages to the object-oriented programming languages, since most of the
1064terminology and literature regarding refactoring comes from the world of
1065object-oriented programming. In addition, the language must have existing tool
1066support for refactoring.
1067
1068The \name{Java} programming language\footnote{\url{https://www.java.com/}} is
1069the dominating language when it comes to example code in the literature of
1070refactoring, and is thus a natural choice. Java is perhaps, currently the most
1071influential programming language in the world, with its \name{Java Virtual
1072Machine} that runs on all of the most popular architectures and also supports
1073dozens of other programming languages\footnote{They compile to Java bytecode.},
1074with \name{Scala}, \name{Clojure} and \name{Groovy} as the most prominent ones.
1075Java is currently the language that every other programming language is compared
1076against. It is also the primary programming language for the author of this
1077thesis.
1078
1079\subsubsection{Choosing the tools}
1080When choosing a tool for manipulating Java, there are certain criteria that
1081have to be met. First of all, the tool should have some existing refactoring
1082support that this thesis can build upon. Secondly it should provide some kind of
1083framework for parsing and analyzing Java source code. Third, it should itself be
1084open source. This is both because of the need to be able to browse the code for
1085the existing refactorings that is contained in the tool, and also because open
1086source projects hold value in them selves. Another important aspect to consider
1087is that open source projects of a certain size, usually has large communities of
1088people connected to them, that are committed to answering questions regarding the
1089use and misuse of the products, that to a large degree is made by the community
1090itself.
1091
1092There is a certain class of tools that meet these criteria, namely the class of
1093\emph{IDEs}\footnote{\emph{Integrated Development Environment}}. These are
1094programs that is meant to support the whole production cycle of a computer
1095program, and the most popular IDEs that support Java, generally have quite good
1096refactoring support.
1097
1098The main contenders for this thesis is the \name{Eclipse IDE}, with the
1099\name{Java development tools} (JDT), the \name{IntelliJ IDEA Community Edition}
1100and the \name{NetBeans IDE} \see{toolSupport}. \name{Eclipse} and
1101\name{NetBeans} are both free, open source and community driven, while the
1102\name{IntelliJ IDEA} has an open sourced community edition that is free of
1103charge, but also offer an \name{Ultimate Edition} with an extended set of
1104features, at additional cost. All three IDEs supports adding plugins to extend
1105their functionality and tools that can be used to parse and analyze Java source
1106code. But one of the IDEs stand out as a favorite, and that is the \name{Eclipse
1107IDE}. This is the most popular\citing{javaReport2011} among them and seems to be
1108de facto standard IDE for Java development regardless of platform.
1109
b4d90424 1110\subsection{The primitive refactorings}
021508ad
EK
1111The refactorings presented here are the primitive refactorings used in this
1112project. They are the abstract building blocks used by the \ExtractAndMoveMethod
1113refactoring.
04e21f15 1114
b4d90424 1115\paragraph{The Extract Method refactoring}
04e21f15
EK
1116The \refa{Extract Method} refactoring is used to extract a fragment of code
1117from its context and into a new method. A call to the new method is inlined
d516ac0b
EK
1118where the fragment was before. It is used to break code into logical units, with
1119names that explain their purpose.
1120
1121An example of an \ExtractMethod refactoring is shown in
1122\myref{lst:extractMethodRefactoring}. It shows a method containing calls to the
1123methods \method{foo} and \method{bar} of a type \type{X}. These statements are
1124then extracted into the new method \method{fooBar}.
d516ac0b 1125
021508ad 1126\begin{listing}[h]
d516ac0b 1127 \begin{multicols}{2}
53be7239 1128 \begin{minted}[samepage,frame=topline,label={Before},framesep=\mintedframesep]{java}
d516ac0b
EK
1129 class C {
1130 void method() {
1131 X x = new X();
1132 x.foo(); x.bar();
1133 }
1134 }
1135 \end{minted}
1136
1137 \columnbreak
1138
53be7239 1139 \begin{minted}[samepage,frame=topline,label={After},framesep=\mintedframesep]{java}
d516ac0b
EK
1140 class C {
1141 void method() {
1142 X x = new X();
1143 fooBar(x);
1144 }
d516ac0b
EK
1145 void fooBar(X x) {
1146 x.foo(); x.bar();
1147 }
1148 }
1149 \end{minted}
1150 \end{multicols}
1151 \caption{An example of an \ExtractMethod refactoring.}
1152 \label{lst:extractMethodRefactoring}
1153\end{listing}
04e21f15 1154
b4d90424 1155\paragraph{The Move Method refactoring}
04e21f15 1156The \refa{Move Method} refactoring is used to move a method from one class to
4306ef44
EK
1157another. This can be appropriate if the method is using more features of another
1158class than of the class which it is currently defined.
1159
1160\Myref{lst:moveMethodRefactoring} shows an example of this refactoring. Here a
1161method \method{fooBar} is moved from the class \type{C} to the class \type{X}.
1162
021508ad 1163\begin{listing}[h]
4306ef44 1164 \begin{multicols}{2}
53be7239 1165 \begin{minted}[samepage,frame=topline,label={Before},framesep=\mintedframesep]{java}
4306ef44
EK
1166 class C {
1167 void method() {
1168 X x = new X();
1169 fooBar(x);
1170 }
1171 void fooBar(X x) {
1172 x.foo(); x.bar();
1173 }
1174 }
1175
1176 class X {
1177 void foo(){/*...*/}
1178 void bar(){/*...*/}
1179 }
1180 \end{minted}
1181
1182 \columnbreak
1183
53be7239 1184 \begin{minted}[samepage,frame=topline,label={After},framesep=\mintedframesep]{java}
4306ef44
EK
1185 class C {
1186 void method() {
1187 X x = new X();
1188 x.fooBar();
1189 }
1190 }
1191
1192 class X {
1193 void fooBar() {
1194 foo(); bar();
1195 }
1196 void foo(){/*...*/}
1197 void bar(){/*...*/}
1198 }
1199 \end{minted}
1200 \end{multicols}
1201 \caption{An example of a \MoveMethod refactoring.}
1202 \label{lst:moveMethodRefactoring}
1203\end{listing}
04e21f15 1204
b4d90424 1205\subsection{The Extract and Move Method refactoring}
021508ad
EK
1206The \ExtractAndMoveMethod refactoring is a composite refactoring composed of the
1207primitive \ExtractMethod and \MoveMethod refactorings. The effect of this
1208refactoring on source code is the same as when extracting a method and moving it
e36eade0 1209to another class. Conceptually, this is done without an intermediate step. In
021508ad
EK
1210practice, as we shall see later, an intermediate step may be necessary.
1211
1212An example of this composite refactoring is shown in
1213\myref{lst:extractAndMoveMethodRefactoring}. The example joins the examples from
1214\cref{lst:extractMethodRefactoring} and \cref{lst:moveMethodRefactoring}. This
1215means that the selection consisting of the consecutive calls to the methods
1216\method{foo} and \method{bar}, is extracted into a new method \method{fooBar}
1217located in the class \type{X}.
1218
1219\begin{listing}[h]
1220 \begin{multicols}{2}
53be7239 1221 \begin{minted}[samepage,frame=topline,label={Before},framesep=\mintedframesep]{java}
021508ad
EK
1222 class C {
1223 void method() {
1224 X x = new X();
1225 x.foo(); x.bar();
1226 }
1227 }
1228
1229 class X {
1230 void foo(){/*...*/}
1231 void bar(){/*...*/}
1232 }
1233 \end{minted}
1234
1235 \columnbreak
1236
53be7239 1237 \begin{minted}[samepage,frame=topline,label={After},framesep=\mintedframesep]{java}
021508ad
EK
1238 class C {
1239 void method() {
1240 X x = new X();
1241 x.fooBar();
1242 }
1243 }
04e21f15 1244
021508ad
EK
1245 class X {
1246 void fooBar() {
1247 foo(); bar();
1248 }
1249 void foo(){/*...*/}
1250 void bar(){/*...*/}
1251 }
1252 \end{minted}
1253 \end{multicols}
1254 \caption{An example of the \ExtractAndMoveMethod refactoring.}
1255 \label{lst:extractAndMoveMethodRefactoring}
1256\end{listing}
04e21f15 1257
b4d90424 1258\subsection{Research questions}
0fe1a611
EK
1259The main question that I seek an answer to in this thesis is:
1260
1261\begin{quote}
1262 Is it possible to automate the analysis and execution of the
1263 \ExtractAndMoveMethod refactoring, and do so for all of the code of a larger
1264 project?
1265\end{quote}
1266
1267\noindent The secondary questions will then be:
1268
1269\paragraph{Can we do this efficiently?} Can we automate the analysis and
1270execution of the refactoring so it can be run in a reasonable amount of time?
1271And what does \emph{reasonable} mean in this context?
1272
1273And, assuming the refactoring does in fact improve the quality of source code:
1274
1275\paragraph{How can the automation of the refactoring be helpful?} What is the
e36eade0 1276usefulness of the refactoring in a software development setting? In what parts
0fe1a611
EK
1277of the development process can the refactoring play a role?
1278
97ae6df1 1279\subsection{Methodology}
b4d90424 1280
97ae6df1
EK
1281\subsubsection{Evolutionary design}
1282In the programming work for this project, it have tried to use a design strategy
1283called evolutionary design, also known as continuous or incremental
1284design\citing{wiki_continuous_2014}. It is a software design strategy
1285advocated by the Extreme Programming community. The essence of the strategy is
1286that you should let the design of your program evolve naturally as your
1287requirements change. This is seen in contrast with up-front design, where
1288design decisions are made early in the process.
70905ddc 1289
97ae6df1
EK
1290The motivation behind evolutionary design is to keep the design of software as
1291simple as possible. This means not introducing unneeded functionality into a
1292program. You should defer introducing flexibility into your software, until it
1293is needed to be able to add functionality in a clean way.
3f929fcc 1294
97ae6df1
EK
1295Holding up design decisions, implies that the time will eventually come when
1296decisions have to be made. The flexibility of the design then relies on the
1297programmer's abilities to perform the necessary refactoring, and \his confidence
1298in those abilities. From my experience working on this project, I can say that
1299this confidence is greatly enhanced by having automated tests to rely on
1300\see{tdd}.
3f929fcc 1301
97ae6df1
EK
1302The choice of going for evolutionary design developed naturally. As Fowler
1303points out in his article \tit{Is Design Dead?}, evolutionary design much
1304resembles the ``code and fix'' development strategy\citing{fowler_design_2004}.
1305A strategy that most of us have practiced in school. This was also the case when
1306I first started this work. I had to learn the inner workings of Eclipse and its
1307refactoring-related plugins. That meant a lot of fumbling around with code I did
1308not know, in a trial and error fashion. Eventually I started writing tests for
1309my code, and my design began to evolve.
1310
1311\subsubsection{Test-driven development}\label{tdd}
1312As mentioned before, the project started out as a classic code and fix
1313developmen process. My focus was aimed at getting something to work, rather than
1314doing so according to best practice. This resulted in a project that got out of
1315its starting blocks, but it was not accompanied by any tests. Hence it was soon
1316difficult to make any code changes with the confidence that the program was
1317still correct afterwards (assuming it was so before changing it). I always knew
1318that I had to introduce some tests at one point, but this experience accelerated
1319the process of leading me onto the path of testing.
1320
1321I then wrote tests for the core functionality of the plugin, and thus gained
1322more confidence in the correctness of my code. I could now perform quite drastic
1323changes without ``wetting my pants``. After this, nearly all of the semantic
1324changes done to the business logic of the project, or the addition of new
1325functionality, was made in a test-driven manner. This means that before
1326performing any changes, I would define the desired functionality through a set
1327of tests. I would then run the tests to check that they were run and that they
1328did not pass. Then I would do any code changes necessary to make the tests
1329pass. The definition of how the program is supposed to operate is then captured
1330by the tests. However, this does not prove the correctness of the analysis
1331leading to the test definitions.
1332
1333\subsubsection{Continuous integration}
1334\todoin{???}
1335
1336\section{Related Work}
1337
1338\subsection{Safer refactorings}
1339\todoin{write}
1340
1341\subsection{The compositional paradigm of refactoring}
1342This paradigm builds upon the observation of Vakilian et
1343al.\citing{vakilian2012}, that of the many automated refactorings existing in
1344modern IDEs, the simplest ones are dominating the usage statistics. The report
1345mainly focuses on \name{Eclipse} as the tool under investigation.
1346
1347The paradigm is described almost as the opposite of automated composition of
1348refactorings \see{compositeRefactorings}. It works by providing the programmer
1349with easily accessible primitive refactorings. These refactorings shall be
1350accessed via keyboard shortcuts or quick-assist menus\footnote{Think
1351quick-assist with Ctrl+1 in \name{Eclipse}} and be promptly executed, opposed to in the
1352currently dominating wizard-based refactoring paradigm. They are meant to
1353stimulate composing smaller refactorings into more complex changes, rather than
1354doing a large upfront configuration of a wizard-based refactoring, before
1355previewing and executing it. The compositional paradigm of refactoring is
1356supposed to give control back to the programmer, by supporting \himher with an
1357option of performing small rapid changes instead of large changes with a lesser
1358degree of control. The report authors hope this will lead to fewer unsuccessful
1359refactorings. It also could lower the bar for understanding the steps of a
1360larger composite refactoring and thus also help in figuring out what goes wrong
1361if one should choose to op in on a wizard-based refactoring.
1362
1363Vakilian and his associates have performed a survey of the effectiveness of the
1364compositional paradigm versus the wizard-based one. They claim to have found
1365evidence of that the \emph{compositional paradigm} outperforms the
1366\emph{wizard-based}. It does so by reducing automation, which seem
1367counterintuitive. Therefore they ask the question ``What is an appropriate level
1368of automation?'', and thus questions what they feel is a rush toward more
1369automation in the software engineering community.
3f929fcc 1370
4e135659 1371
a5317dcf 1372
aceb848c 1373\chapter{The search-based Extract and Move Method refactoring}
9503a520
EK
1374In this chapter I will delve into the workings of the search-based
1375\ExtractAndMoveMethod refactoring. We will see the choices it must make along
1376the way and why it chooses a text selection as a candidate for refactoring or
1377not.
1378
e36eade0 1379After defining some concepts, I will introduce an example that will be used
9503a520
EK
1380throughout the chapter to illustrate how the refactoring works in some simple
1381situations.
c894b297
EK
1382
1383\section{The inputs to the refactoring}
1384For executing an \ExtractAndMoveMethod refactoring, there are two simple
f5355077 1385requirements. The first thing the refactoring needs is a text selection, telling
c894b297
EK
1386it what to extract. Its second requirement is a target for the subsequent move
1387operation.
1388
1389The extracted method must be called instead of the selection that makes up its
1390body. Also, the method call has to be performed via a variable, since the method
aceb848c
EK
1391is not static. Therefore, the move target must be a variable in the scope of the
1392extracted selection. The actual new location for the extracted method will be
1393the class representing the type of the move target variable. But, since the
1394method also must be called through a variable, it makes sense to define the move
1395target to be either a local variable or a field in the scope of the text
1396selection.
c894b297 1397
53be7239
EK
1398\section{Defining a text selection}
1399A text selection, in our context, is very similar to what you think of when
1400selecting a bit of text in your editor or other text processing tool with your
1401mouse or keyboard. It is an abstract construct that is meant to capture which
1402specific portion of text we are about to deal with.
1403
1404To be able to clearly reason about a text selection done to a portion of text in
1405a computer file, that consist of pure text, we put up the following definition.
1406
1407\definition{A \emph{text selection} in a text file is defined by two
1408non-negative integers, in addition to a reference to the file itself. The first
1409integer is an offset into the file, while the second reference is the length of
1410the text selection.}
1411
1412This means that the selected text consist of a number of characters equal to the
1413length of the selection, where the first character is found at the specified
1414offset.
1415
b4d90424
EK
1416\section{Where we look for text selections}
1417
1418\subsection{Text selections are found in methods}
1419The text selections we are interested in are those that surrounds program
1420statements. Therefore, the place we look for selections that can form candidates
1421for an execution of the \ExtractAndMoveMethod refactoring, is within the body of
1422a single method.
1423
1424\paragraph{On ignoring static methods}
1425In this project we are not analyzing static methods for candidates to the
1426\ExtractAndMoveMethod refactoring. The reason for this is that in the cases
1427where we want to perform the refactoring for a selection within a static method,
1428the first step is to extract the selection into a new method. Hence this method
1429also become static, since it must be possible to call it from a static context.
1430It would then be difficult to move the method to another class, make it
1431non-static and calling it through a variable. To avoid these obstacles, we
1432simply ignore static methods.
1433
53be7239
EK
1434\begin{listing}[htb]
1435\def\charwidth{5.8pt}
9db7f4cf 1436\def\indent{2*\charwidth}
53be7239
EK
1437\def\lineheight{\baselineskip}
1438\def\mintedtop{2*\lineheight+5.8pt}
1439
1440\begin{tikzpicture}[overlay, yscale=-1, xshift=3.8pt+\charwidth*31]
1441 \tikzstyle{overlaybox}=[fill=lightgray,opacity=0.2]
1442 % Level 1
1443 \draw[overlaybox] (\indent,\mintedtop+\lineheight*4) rectangle
9db7f4cf 1444 +(23*\charwidth,17*\lineheight);
53be7239
EK
1445
1446 % Level 2
1447 \draw[overlaybox] (2*\indent,\mintedtop+5*\lineheight) rectangle
9db7f4cf 1448 +(15*\charwidth,3*\lineheight);
53be7239 1449 \draw[overlaybox] (2*\indent,\mintedtop+15*\lineheight) rectangle
9db7f4cf 1450 +(15*\charwidth,3*\lineheight);
53be7239 1451 \draw[overlaybox] (2*\indent,\mintedtop+19*\lineheight) rectangle
9db7f4cf 1452 +(15*\charwidth,\lineheight);
53be7239
EK
1453\end{tikzpicture}
1454 \begin{multicols}{2}
01d46361 1455 \begin{minted}[linenos,frame=topline,label=Clean,framesep=\mintedframesep]{java}
53be7239 1456class C {
9db7f4cf
EK
1457 A a; B b; boolean bool;
1458
1459 void method(int val) {
1460 if (bool) {
1461 a.foo();
1462 a = new A();
1463 a.bar();
1464 }
1465
1466 a.foo();
1467 a.bar();
1468
1469 switch (val) {
1470 case 1:
1471 b.a.foo();
1472 b.a.bar();
1473 break;
1474 default:
1475 a.foo();
53be7239 1476 }
9db7f4cf 1477 }
53be7239
EK
1478}
1479\end{minted}
1480
1481\columnbreak
1482
9db7f4cf
EK
1483\begin{minted}[frame=topline,label={With statement
1484 sequences},framesep=\mintedframesep]{java}
53be7239 1485class C {
9db7f4cf
EK
1486 A a; B b; boolean bool;
1487
1488 void method(int val) {
1489 if (bool) {
1490 a.foo();
1491 a = new A();
1492 a.bar();
53be7239 1493 }
9db7f4cf
EK
1494
1495 a.foo();
1496 a.bar();
1497
1498 switch (val) {
1499 case 1:
1500 b.a.foo();
1501 b.a.bar();
1502 break;
1503 default:
1504 a.foo();
1505 }
1506 }
53be7239
EK
1507}
1508\end{minted}
1509
1510 \end{multicols}
1511\caption{Classes \type{A} and \type{B} are both public. The methods
1512\method{foo} and \method{bar} are public members of class \type{A}.}
1513\label{lst:grandExample}
1514\end{listing}
1515
b4d90424 1516\subsection{The possible text selections of a method body}
0cbeeadb 1517\todoin{dummy todo}
b4d90424
EK
1518The number of possible text selections that can be made from the text in a
1519method body, are equal to all the sub-sequences of characters within it. For our
f5355077
EK
1520purposes, analyzing program source code, we must define what it means for a text
1521selection to be valid.
53be7239
EK
1522
1523\definition{A \emph{valid text selection} is a text selection that contains all
1524of one or more consecutive program statements.}
1525
1526For a sequence of statements, the text selections that can be made from it, are
1527equal to all its sub-sequences. \Myref{lst:textSelectionsExample} show an
1528example of all the text selections that can be made from the code in
e36eade0 1529\myref{lst:grandExample}, lines 16-18. For convenience and the clarity of this
01d46361
EK
1530example, the text selections are represented as tuples with the start and end
1531line of all selections: $\{(16), (17), (18), (16,17), (16,18), (17,18)\}$.
53be7239
EK
1532
1533\begin{listing}[htb]
1534\def\charwidth{5.7pt}
1535\def\indent{4*\charwidth}
1536\def\lineheight{\baselineskip}
01d46361 1537\def\mintedtop{\lineheight-1pt}
53be7239
EK
1538
1539\begin{tikzpicture}[overlay, yscale=-1]
1540 \tikzstyle{overlaybox}=[fill=lightgray,opacity=0.2]
1541
1542 % First statement
1543 \draw[overlaybox] (2*\charwidth,\mintedtop) rectangle
1544 +(16*\charwidth,\lineheight);
1545
1546 % Second statement
1547 \draw[overlaybox] (2*\charwidth,\mintedtop+\lineheight) rectangle
1548 +(16*\charwidth,\lineheight);
1549
1550 % Third statement
1551 \draw[overlaybox] (2*\charwidth,\mintedtop+2*\lineheight) rectangle
1552 +(16*\charwidth,\lineheight);
1553
1554 \draw[overlaybox] (\indent-3*\charwidth,\mintedtop) rectangle
1555 +(18*\charwidth,2*\lineheight);
1556
1557 \draw[overlaybox] (3*\charwidth,\mintedtop+\lineheight) rectangle
1558 +(14*\charwidth,2*\lineheight);
1559
1560 % All
1561 \draw[overlaybox] (\indent,\mintedtop) rectangle
1562 +(12*\charwidth,3*\lineheight);
1563\end{tikzpicture}
1564% indent should be 5 spaces
9503a520 1565\begin{minted}[linenos,firstnumber=16]{java}
53be7239
EK
1566 b.a.foo();
1567 b.a.bar();
1568 break;
1569\end{minted}
1570\caption{Example of how the text selections generator would generate text
1571 selections based on a lists of statements. Each highlighted rectangle
1572represents a text selection.}
1573\label{lst:textSelectionsExample}
1574\end{listing}
1575
1576Each nesting level of a method body can have many such sequences of statements.
9503a520 1577The outermost nesting level has one such sequence, and each branch contains
01d46361
EK
1578their own sequence of statements. \Myref{lst:grandExample} has a version of some
1579code where all such sequences of statements are highlighted for a method body.
47c0bea8 1580
9503a520
EK
1581To complete our example of possible text selections, I will now list all
1582possible text selections for the method in \myref{lst:grandExample}, by nesting
f5355077 1583level. There are 23 of them in total.
47c0bea8 1584
9503a520
EK
1585\begin{description}
1586 \item[Level 1 (10 selections)] \hfill \\
1587 $\{(5,9), (11), (12), (14,21), (5,11), (5,12), (5,21), (11,12),
1588 (11,21), \\(12,21)\}$
8de7cf3c 1589
9503a520
EK
1590 \item[Level 2 (13 selections)] \hfill \\
1591 $\{(6), (7), (8), (6,7), (6,8), (7,8), (16), (17), (18), (16,17), (16,18), \\
1592 (17,18), (20)\}$
1593\end{description}
c894b297 1594
b4d90424
EK
1595\subsubsection{The complexity}\label{sec:complexity}
1596The complexity of how many text selections that needs to be analyzed for a body
1597of in total $n$ statements, is bounded by $O(n^2)$. A body of statements is here
1598all the statements in all nesting levels of a sequence of statements. A method
1599body (or a block) is a body of statements. To prove that the complexity is
1600bounded by $O(n^2)$, I present a couple of theorems and proves them.
1601
1602\begin{theorem}
1603The number of text selections that need to be analyzed for each list of
1604statements of length $n$, is exactly
1605
1606\begin{equation*}
1607 \sum_{i=1}^{n} i = \frac{n(n+1)}{2}
1608 \label{eq:complexityStatementList}
1609\end{equation*}
1610\label{thm:numberOfTextSelection}
1611\end{theorem}
1612
1613\begin{proof}
1614 For $n=1$ this is trivial: $\frac{1(1+1)}{2} = \frac{2}{2} = 1$. One statement
1615 equals one selection.
1616
1617 For $n=2$, you get one text selection for the first statement, one selection
1618 for the second statement, and one selection for the two of them combined.
1619 This equals three selections. $\frac{2(2+1)}{2} = \frac{6}{2} = 3$.
1620
1621 For $n=3$, you get 3 selections for the two first statements, as in the case
1622 where $n=2$. In addition you get one selection for the third statement itself,
1623 and two more statements for the combinations of it with the two previous
1624 statements. This equals six selections. $\frac{3(3+1)}{2} = \frac{12}{2} = 6$.
1625
1626 Assume that for $n=k$ there exists $\frac{k(k+1)}{2}$ text selections. Then we
1627 want to add selections for another statement, following the previous $k$
1628 statements. So, for $n=k+1$, we get one additional selection for the statement
1629 itself. Then we get one selection for each pair of the new selection and the
1630 previous $k$ statements. So the total number of selections will be the number
1631 of already generated selections, plus $k$ for every pair, plus one for the
1632 statement itself: $\frac{k(k+1)}{2} + k +
1633 1 = \frac{k(k+1)+2k+2}{2} = \frac{k(k+1)+2(k+1)}{2} = \frac{(k+1)(k+2)}{2} =
1634 \frac{(k+1)((k+1)+1)}{2} = \sum_{i=1}^{k+1} i$
1635\end{proof}
1636
1637%\definition{A \emph{body of statements} is a sequence of statements where every
1638%statement may have sub-statements.}
1639
1640\begin{theorem}
1641 The number of text selections for a body of statements is maximized if all the
1642 statements are at the same level.
1643 \label{thm:textSelectionsMaximized}
1644\end{theorem}
1645
1646\begin{proof}
1647 Assume we have a body of, in total, $k$ statements. Then, the sum of the
1648 lengths of all the lists of statements in the body, is also $k$. Let
1649 $\{l,\ldots,m,(k-l-\ldots-m)\}$ be the lengths of the lists of statements in
1650 the body, with $l+\ldots+m<k \Rightarrow \forall i \in \{l,\ldots,m\} : i < k$.
1651
1652 Then, the number of text selections that are generated for the $k$ statements
1653 is
1654
1655 {
1656 \small
1657 \begin{align*}
1658 \frac{l(l+1)}{2} + \ldots + \frac{m(m+1)}{2} +
1659 \frac{(k-l-\ldots-m)((k-l-\ldots-m)+ 1)}{2} = \\
1660 \frac{l^2+l}{2} + \ldots + \frac{m^2+m}{2} + \frac{k^2 - 2kl - \ldots - 2km +
1661 l^2 + \ldots + m^2 + k - l - \ldots - m}{2} = \\
1662 \frac{2l^2 - 2kl + \ldots + 2m^2 - 2km + k^2 + k}{2}
1663 \end{align*}
1664 }
1665
1666 \noindent It then remains to show that this inequality holds:
1667
1668 \begin{align*}
1669 \frac{2l^2 - 2kl + \ldots + 2m^2 - 2km + k^2 + k}{2} < \frac{k(k+1)}{2} =
1670 \frac{k^2 + k}{2}
1671 \end{align*}
1672
1673 \noindent By multiplication by $2$ on both sides, and by removing the equal
1674 parts, we get
1675
1676 \begin{align*}
1677 2l^2 - 2kl + \ldots + 2m^2 - 2km < 0
1678 \end{align*}
1679
1680 Since $\forall i \in \{l,\ldots,m\} : i < k$, we have that $\forall i \in
1681 \{l,\ldots,m\} : 2ki > 2i^2$, so all the pairs of parts on the form $2i^2-2ki$
1682 are negative. In sum, the inequality holds.
1683
1684\end{proof}
1685
1686Therefore, the complexity for the number of selections that needs to be analyzed
1687for a body of $n$ statements is $O\bigl(\frac{n(n+1)}{2}\bigr) = O(n^2)$.
1688
0cc6a67d 1689\section{Disqualifying a selection}
1c521a77
EK
1690Certain text selections would lead to broken code if used as input to the
1691\ExtractAndMoveMethod refactoring. To avoid this, we have to check all text
f5355077
EK
1692selections for such conditions before they are further analyzed. This section
1693is therefore going to present some properties that make a selection unsuitable
15327961 1694for our refactoring.
1c521a77
EK
1695
1696\subsection{A call to a protected or package-private method}
21506154
EK
1697If a text selection contains a call to a protected or package-private method, it
1698would not be safe to move it to another class. The reason for this, is that we
1699cannot know if the called method is being overridden by some subclass of the
1700\gloss{enclosingClass}, or not.
1c521a77
EK
1701
1702Imagine that the protected method \method{foo} is declared in class \m{A},
1703and overridden in class \m{B}. The method \method{foo} is called from within a
1704selection done to a method in \m{A}. We want to extract and move this selection
1705to another class. The method \method{foo} is not public, so the \MoveMethod
1706refactoring must make it public, making the extracted method able to call it
f5355077 1707from the extracted method's new location. The problem is, that the now public
1c521a77
EK
1708method \method{foo} is overridden in a subclass, where it has a protected
1709status. This makes the compiler complain that the subclass \m{B} is trying to
1710reduce the visibility of a method declared in its superclass \m{A}. This is not
21506154 1711allowed in Java, and for good reasons. It would make it possible to make a
1c521a77 1712subclass that could not be a substitute for its superclass.
1c521a77 1713
21506154
EK
1714The problem this check helps to avoid, is a little subtle. The problem does not
1715arise in the class where the change is done, but in a class derived from it.
1716This shows that classes acting as superclasses are especially fragile to
b4d90424
EK
1717introducing errors in the context of automated refactoring.
1718\begin{comment}
1719This is also shown in bug\ldots \todoin{File Eclipse bug report}
1720\end{comment}
21506154 1721
1fceb439
EK
1722\subsection{A double class instance creation}
1723The following is a problem caused solely by the underlying \MoveMethod
1724refactoring. The problem occurs if two classes are instantiated such that the
1725first constructor invocation is an argument to a second, and that the first
1726constructor invocation takes an argument that is built up using a field. As an
1727example, say that \var{name} is a field of the enclosing class, and we have the
1728expression \code{new A(new B(name))}. If this expression is located in a
1729selection that is moved to another class, \var{name} will be left untouched,
1730instead of being prefixed with a variable of the same type as it is declared in.
1731If \var{name} is the destination for the move, it is not replaced by
1732\code{this}, or removed if it is a prefix to a member access
1733(\code{name.member}), but it is still left by itself.
1734
1735Situations like this would lead to code that will not compile. Therefore, we
1736have to avoid them by not allowing selections to contain such double class
1737instance creations that also contains references to fields.
b4d90424 1738\begin{comment}
1fceb439 1739\todoin{File Eclipse bug report}
b4d90424 1740\end{comment}
1fceb439 1741
1c521a77
EK
1742\subsection{Instantiation of non-static inner class}
1743When a non-static inner class is instantiated, this must happen in the scope of
1744its declaring class. This is because it must have access to the members of the
1745declaring class. If the inner class is public, it is possible to instantiate it
1746through an instance of its declaring class, but this is not handled by the
1747underlying \MoveMethod refactoring.
1748
1749Performing a move on a method that instantiates a non-static inner class, will
1750break the code if the instantiation is not handled properly. For this reason,
1751selections that contains instantiations of non-static inner classes are deemed
1752unsuitable for the \ExtractAndMoveMethod refactoring.
1753
1754\subsection{References to enclosing instances of the enclosing class}
1755The title of this section may be a little hard to grasp at first. What it means
1756is that there is a (non-static) class \m{C} that is declared in the scope of
98b06ec2
EK
1757possibly multiple other classes. And there is a statement in the body of a
1758method declared in class \m{C}, that contains a reference to one or more
1759instances of these enclosing classes of \m{C}.
1c521a77
EK
1760
1761The problem with this, is that these references may not be valid if they are
1762moved to another class. Theoretically, some situations could easily be solved by
1763passing, to the moved method, a reference to the instance where the problematic
98b06ec2
EK
1764referenced member is declared. This should work in the case where this member is
1765publicly accessible. This is not done in the underlying \MoveMethod refactoring,
1766so it cannot be allowed in the \ExtractAndMoveMethod refactoring either.
1c521a77 1767
15327961 1768\subsection{Inconsistent return statements}
cb903a13
EK
1769To verify that a text selection is consistent with respect to return statements,
1770we must check that if a selection contains a return statement, then every
1771possible execution path within the selection ends in either a return or a throw
15327961
EK
1772statement. This property is important regarding the \ExtractMethod refactoring.
1773If it holds, it means that a method could be extracted from the selection, and a
1774call to it could be substituted for the selection. If the method has a non-void
1775return type, then a call to it would also be a valid return point for the
1776calling method. If its return value is of the void type, then the \ExtractMethod
1777refactoring will append an empty return statement to the back of the method
1778call. Therefore, the analysis does not discriminate on either kinds of return
1779statements, with or without a return value.
1780
cb903a13
EK
1781A throw statement is accepted anywhere a return statement is required. This is
1782because a throw statement causes an immediate exit from the current block,
1783together with all outer blocks in its control flow that does not catch the
1784thrown exception.
15327961
EK
1785
1786Return statements can be either explicit or implicit. An \emph{explicit} return
1787statement is formed by using the \code{return} keyword, while an \emph{implicit}
d59e3ab7
EK
1788return statement is a statement that is not formed using \code{return}, but must
1789be the last statement of a method that can have any side effects. This can
1790happen in methods with a void return type. An example is a statement that is
15327961 1791inside one or more blocks. The last statement of a method could for instance be
cb903a13
EK
1792a synchronized statement, but the last statement that is executed in the method,
1793and that can have any side effects, may be located inside the body of the
1794synchronized statement.
15327961
EK
1795
1796We can start the check for this property by looking at the last statement of a
d59e3ab7
EK
1797selection to see if it is a return statement (explicit or implicit) or a throw
1798statement. If this is the case, then the property holds, assuming the selected
1799code does not contain any compilation errors. All execution paths within the
1800selection should end in either this, or another, return or throw statement.
15327961
EK
1801\todoin{State somewhere that we assume no compilation errors?}
1802
1803If the last statement of the selection is not a return or throw, the execution
d59e3ab7
EK
1804of it must eventually end in one for the selection to be legal. This means that
1805all branches of the last statement of every branch must end in a return or
1806throw. Given this recursive definition, there are only five types of statements
1807that are guaranteed to end in a return or throw if their child branches does.
1808All other statements would have to be considered illegal. The first three:
1809Block-statements, labeled statements and do-statements are all kinds of
1810fall-through statements that always gets their body executed. Do-statements
1811would not make much sense if written such that they
15327961
EK
1812always ends after the first round of execution of their body, but that is not
1813our concern. The remaining two statements that can end in a return or throw are
1814if-statements and try-statements.
1815
cb903a13 1816For an if-statement, the rule is that if its then-part does not contain any
d59e3ab7 1817return or throw statements, this is considered illegal. If the then-part does
cb903a13
EK
1818contain a return or throw, the else-part is checked. If its else-part is
1819non-existent, or it does not contain any return or throw statements, the
1820statement is considered illegal. If an if-statement is not considered illegal,
d59e3ab7 1821the bodies of its two parts must be checked.
15327961 1822
cb903a13
EK
1823Try-statements are handled much the same way as if-statements. The body of a
1824try-statement must contain a return or throw. The same applies to its catch
1825clauses and finally body.
1c521a77 1826
11d9e6e1
EK
1827\subsection{Ambiguous return values}
1828The problem with ambiguous return values arise when a selection is chosen to be
1829extracted into a new method, but it needs to return more than one value from
1830that method.
1831
1832This problem occurs in two situations. The first situation arise when there is
1833more than one local variable that is both assigned to within a selection and
1834also referenced after the selection. The other situation occur when there is
1835only one such assignment, but the selection also contain return statements.
1836
1837Therefore we must examine the selection for assignments to local variables that
1838are referenced after the text selection. Then we must verify that not more than
1839one such reference is done, or zero if any return statements are found.
1840
83f12332
EK
1841\subsection{Illegal statements}
1842An illegal statement may be a statement that is of a type that is never allowed,
8fa89d14
EK
1843or it may be a statement of a type that is only allowed if certain conditions
1844are true.
83f12332
EK
1845
1846Any use of the \var{super} keyword is prohibited, since its meaning is altered
1847when moving a method to another class.
1848
1849For a \emph{break} statement, there are two situations to consider: A break
1850statement with or without a label. If the break statement has a label, it is
1851checked that whole of the labeled statement is inside the selection. If the
1852break statement does not have a label attached to it, it is checked that its
1853innermost enclosing loop or switch statement also is inside the selection.
1854
1855The situation for a \emph{continue} statement is the same as for a break
1856statement, except that it is not allowed inside switch statements.
1857
1858Regarding \emph{assignments}, two types of assignments are allowed: Assignments
1859to non-final variables and assignments to array access. All other assignments
1860are regarded illegal.
1861
1862\todoin{Expand with more illegal statements and/or conclude that I did not have
9503a520
EK
1863time to analyze all statement types.}
1864
01d46361
EK
1865\section{Disqualifying selections from the
1866example}\label{sec:disqualifyingExample}
9503a520
EK
1867Among the selections we found for the code in \myref{lst:grandExample}, not many
1868of them must be disqualified on the basis of containing something illegal. The
1869only statement causing trouble is the break statement in line 18. None of the
1870selections on nesting level 2 can contain this break statement, since the
1871innermost switch statement is not inside any of these selections.
83f12332 1872
9503a520
EK
1873This means that the text selections $(18)$, $(16,18)$ and $(17,18)$ can be
1874excluded from further consideration, and we are left with the following
1875selections.
81cf9554 1876
9503a520
EK
1877\begin{description}
1878 \item[Level 1 (10 selections)] \hfill \\
1879 $\{(5,9), (11), (12), (14,21), (5,11), (5,12), (5,21), (11,12),
1880 (11,21), \\(12,21)\}$
1881
1882 \item[Level 2 (10 selections)] \hfill \\
1883 $\{(6), (7), (8), (6,7), (6,8), (7,8), (16), (17), (16,17), (20)\}$
1884\end{description}
1885
1886\section{Finding a move target}
1887In the analysis needed to perform the \ExtractAndMoveMethod refactoring
1888automatically, the selection we choose is found among all the selections that
1889has a possible move target. Therefore, the best possible move target must be
1890found for all the candidate selections, so that we are able to sort out the
1891selection that is best suited for the refactoring.
1892
1893To find the best move target for a specific text selection, we first need to
1894find all the possible targets. Since the target must be a local variable or a
1895field, we are basically looking for names within the selection; names that
1896represents references to variables.
1897
1898The names we are looking for, we call prefixes. This is because we are not
1899interested in names that occur in the middle of a dot-separated sequence of
1900names. We are only interested in names that constitutes prefixes of other names,
1901possibly themselves. The reason for this, is that two lexically equal names need
1902not be referencing the same variable, if they themselves are not referenced via
1903the same prefix. Consider the two method calls \code{a.x.foo()} and
1904\code{b.x.foo()}. Here, the two references to \code{x}, in the middle of the
1905qualified names both preceding \code{foo()}, are not referencing the same
1906variable. Even though the variables may share the type, and the method
1907\method{foo} thus is the same for both, we would not know through which of the
1908variables \var{a} or \var{b} we should call the extracted method.
1909
1910The possible move targets are then the prefixes that are not among a subset of
1911the prefixes that are not valid move targets \see{s:unfixes}. Also, prefixes
1912that are just simple names, and have only one occurrence, are left out. This is
1913because they are not going to have any positive effect on coupling between
01d46361 1914classes, and are only going to increase the complexity of the code.
9503a520
EK
1915
1916For finding the best move target among these safe prefixes, a simple heuristic
1917is used. It is as simple as choosing the prefix that is most frequently
1918referenced within the selection.
1919
1920\section{Unfixes}\label{s:unfixes}
1921The prefixes that are not valid as move targets are called unfixes.
1922
1923An unfix can be a name that is assigned to within a selection. The reason that
1924this cannot be allowed, is that the result would be an assignment to the
1925\type{this} keyword, which is not valid in Java \see{eclipse_bug_420726}.
1926
1927Prefixes that originates from variable declarations within the same selection
1928are also considered unfixes. This is because when a method is moved, it needs to
1929be called through a variable. If this variable is also declared within the
1930method that is to be moved, this obviously cannot be done.
1931
1932Also considered as unfixes are variable references that are of types that are
1933not suitable for moving methods to. This can either be because it is not
1934physically possible to move a method to the desired class or that it will cause
1935compilation errors by doing so.
1936
1937If the type binding for a name is not resolved it is considered and unfix. The
1938same applies to types that is only found in compiled code, so they have no
1939underlying source that is accessible to us. (E.g. the \type{java.lang.String}
1940class.)
1941
1942Interfaces types are not suitable as targets. This is simply because interfaces
1943in Java cannot contain methods with bodies. (This thesis does not deal with
1944features of Java versions later than Java 7. Java 8 has interfaces with default
1945implementations of methods.)
1946
1947Neither are local types allowed. This accounts for both local and anonymous
1948classes. Anonymous classes are effectively the same as interface types with
1949respect to unfixes. Local classes could in theory be used as targets, but this
1950is not possible due to limitations of the way the \refa{Extract and Move Method}
1951refactoring has to be implemented. The problem is that the refactoring is done
1952in two steps, so the intermediate state between the two refactorings would not
1953be legal Java code. In the intermediate step for the case where a local class is
1954the move target, the extracted method would need to take the local class as a
1955parameter. This new method would need to live in the scope of the declaring
1956class of the originating method. The local class would then not be in the scope
1957of the extracted method, thus bringing the source code into an illegal state.
1958One could imagine that the method was extracted and moved in one operation,
1959without an intermediate state. Then it would make sense to include variables
1960with types of local classes in the set of legal targets, since the local classes
1961would then be in the scopes of the method calls. If this makes any difference
1962for software metrics that measure coupling would be a different discussion.
1963
1964
1965\begin{listing}[htb]
1966\begin{multicols}{2}
1967\begin{minted}[frame=topline,label=Before,framesep=\mintedframesep]{java}
1968void declaresLocalClass() {
1969 class LocalClass {
1970 void foo() {}
1971 void bar() {}
1972 }
1973
1974 LocalClass inst =
1975 new LocalClass();
1976 inst.foo();
1977 inst.bar();
1978}
1979\end{minted}
1980
1981\columnbreak
1982
1983\begin{minted}[frame=topline,label={After Extract
1984 Method},framesep=\mintedframesep]{java}
1985void declaresLocalClass() {
1986 class LocalClass {
1987 void foo() {}
1988 void bar() {}
1989 }
1990
1991 LocalClass inst =
1992 new LocalClass();
1993 fooBar(inst);
1994}
81cf9554 1995
9503a520
EK
1996// Intermediate step
1997void fooBar(LocalClass inst) {
1998 inst.foo();
1999 inst.bar();
2000}
2001\end{minted}
2002\end{multicols}
2003\caption{When the \refa{Extract and Move Method} tries to use a variable with a
2004local type as the move target, an intermediate step is performed that is not
2005allowed. Here: \type{LocalClass} is not in the scope of \method{fooBar} in its
2006intermediate location.}
2007\label{lst:extractMethod_LocalClass}
2008\end{listing}
83f12332 2009
9503a520 2010The last class of names that are considered unfixes are names used in null
01d46361
EK
2011tests. These are tests that reads like this: if \code{<name>} equals \var{null}
2012then do something. If allowing variables used in those kinds of expressions as
2013targets for moving methods, we would end up with code containing boolean
2014expressions like \code{this == null}, which would not be meaningful, since
2015\var{this} would never be \var{null}.
2016
4ea21603 2017\section{Finding the example selections that have possible targets}
01d46361
EK
2018We now pick up the thread from \myref{sec:disqualifyingExample} where we have a
2019set of text selections that needs to be analyzed to find out if some of them are
2020suitable targets for the \ExtractAndMoveMethod refactoring.
2021
2022We start by analyzing the text selections for nesting level 2, because these
2023results can be used to reason about the selections for nesting level 1. First we
2024have all the single-statement selections.
2025
2026\begin{description}
2027 \item[Selections $(6)$, $(8)$ and $(20)$.] \hfill \\
2028 All these selections have a prefix that contains a possible target, namely
e36eade0
EK
2029 the variable \var{a}. The problem is that the prefixes are only one segment
2030 long, and their frequency counts are only 1 as well. None of these
01d46361
EK
2031 selections are therefore considered as suitable candidates for the
2032 refactoring.
2033
2034 \item[Selection $(7)$.] \hfill \\
2035 This selection contains the unfix \var{a}, and no other possible targets.
2036 The reason for \var{a} being an unfix is that it is assigned to within the
2037 selection. Selection $(7)$ is therefore unsuited as a refactoring candidate.
2038
2039 \item[Selections $(16)$ and $(17)$.] \hfill \\
2040 These selections both have a possible target. The target for both selections
2041 is the variable \var{b}. Both the prefixes have frequency 1. We denote this
2042 with the new tuples $((16), \texttt{b.a}, f(1))$ and $((17), \texttt{b.a},
2043 f(1))$. They contain the selection, the prefix with the target and the
e36eade0 2044 frequency for this prefix.
01d46361
EK
2045
2046\end{description}
2047
2048Then we have all the text selections from level 2 that are composed of multiple
2049statements:
2050
2051\begin{description}
2052 \item[Selections $(6,7)$, $(6,8)$ and $(7,8)$.] \hfill \\
2053 All these selections are disqualified for the reason that they contain the
2054 unfix \var{a}, due to the assignment, and no other possible move targets.
2055
2056 \item[Selection $(16,17)$.] \hfill \\
e36eade0
EK
2057 This selection is the last selection that is not analyzed on nesting level
2058 2. It contains only one possible move target, and that is the variable
2059 \var{b}. It also contains only one prefix \var{b.a}, with frequency count
2060 2. Therefore we have a new candidate $((16,17), \texttt{b.a}, f(2))$.
01d46361
EK
2061
2062\end{description}
2063
2064Moving on to the text selections for nesting level 1, starting with the
2065single-statement selections:
2066
2067\begin{description}
2068 \item[Selection $(5,9)$.] \hfill \\
e36eade0 2069 This selection contains two variable references that must be analyzed to see
01d46361
EK
2070 if they are possible move candidates. The first one is the variable
2071 \var{bool}. This variable is of type \type{boolean}, that is a primary type
2072 and therefore not possible to make any changes to. The second variable is
2073 \var{a}. The variable \var{a} is an unfix in $(5,9)$, for the same reason as
2074 in the selections $(6,7)$, $(7,8)$ and $(6,8)$. So selection $(5,9)$
2075 contains no possible move targets.
2076
2077 \item[Selections $(11)$ and $(12)$.] \hfill \\
2078 These selections are disqualified for the same reasons as selections $(6)$
2079 and $(8)$. Their prefixes are one segment long and are referenced only one
2080 time.
2081
2082 \item[Selection $(14,21)$] \hfill \\
2083 This is the switch statement from \myref{lst:grandExample}. It contains the
2084 relevant variable references \var{val}, \var{a} and \var{b}. The variable
2085 \var{val} is a primary type, just as \var{bool}. The variable \var{a} is
2086 only found in one statement, and in a prefix with only one segment, so it is
2087 not considered to be a possible move target. The only variable left is
2088 \var{b}. Just as in the selection $(16,17)$, \var{b} is part of the prefix
e36eade0 2089 \code{b.a}, that has 2 appearances. We have found a new candidate $((14,21),
01d46361
EK
2090 \texttt{b.a}, f(2))$.
2091
2092\end{description}
2093
e36eade0 2094It remains to see if we get any new candidates by analyzing the multi-statement
01d46361 2095text selections for nesting level 1:
9503a520 2096
01d46361
EK
2097\begin{description}
2098 \item[Selections $(5,11)$ and $(5,12)$.] \hfill \\
e36eade0 2099 These selections are disqualified for the same reason as $(5,9)$. The only
01d46361
EK
2100 possible move target \var{a} is an unfix.
2101
2102 \item[Selection $(5,21)$.] \hfill \\
2103 This is whole of the method body in \myref{lst:grandExample}. The variables
2104 \var{a}, \var{bool} and \var{val} are either an unfix or primary types. The
2105 variable \var{b} is the only possible move target, and we have, again, the
2106 prefix \code{b.a} as the center of attention. The refactoring candidate is
2107 $((5,21), \texttt{b.a}, f(2))$.
2108
2109 \item[Selection $(11,12)$.] \hfill \\
2110 This small selection contains the prefix \code{a} with frequency 2, and no
2111 unfixes. The candidate is $((11,12), \texttt{a}, f(2))$.
2112
2113 \item[Selection $(11,21)$] \hfill \\
2114 This selection contains the selection $(11,12)$ in addition to the switch
2115 statement. The selection has two possible move targets. The first one is
e36eade0 2116 \var{b}, in a prefix with frequency 2. The second is \var{a}, although it
01d46361
EK
2117 is in a simple prefix, it is referenced 3 times, and is therefore chosen
2118 as the target for the selection. The new candidate is $((11,21),
2119 \texttt{a}, f(3))$.
2120
2121 \item[Selection $(12,21)$.] \hfill \\
2122 This selection is similar to the previous $(11,21)$, only that \var{a} now
e36eade0 2123 has frequency count 2. This means that the prefixes \code{a} and
01d46361
EK
2124 \code{b.a} both have the count 2. Of the two, \code{b.a} is preferred,
2125 since it has more segments than \code{a}. Thus the candidate for this
2126 selection is $((12,21), \texttt{b.a}, f(2))$.
2127
2128\end{description}
2129
2130For the method in \myref{lst:grandExample} we therefore have the following 8
2131candidates for the \ExtractAndMoveMethod refactoring: $\{((16), \texttt{b.a},
2132f(1)), ((17), \texttt{b.a}, f(1)), ((16,17), \texttt{b.a}, f(2)), ((14,21),
2133\texttt{b.a}, f(2)), \\ ((5,21), \texttt{b.a}, f(2)), ((11,12), \texttt{a},
2134f(2)), ((11,21), \texttt{a}, f(3)), ((12,21), \texttt{b.a}, f(2))\}$.
2135
2136It now only remains to specify an order for these candidates, so we can choose
2137the most suitable one to refactor.
9503a520 2138
01d46361
EK
2139
2140\section{Choosing the selection}\label{sec:choosingSelection}
9503a520
EK
2141When choosing a selection between the text selections that have possible move
2142targets, the selections need to be ordered. The criteria below are presented in
2143the order they are prioritized. If not one selection is favored over the other
2144for a concrete criterion, the selections are evaluated by the next criterion.
2145
2146\begin{enumerate}
2147 \item The first criterion that is evaluated is whether a selection contains
01d46361
EK
2148 any unfixes or not. If selection \m{A} contains no unfixes, while selection
2149 \m{B} does, selection \m{A} is favored over selection \m{B}. This is
2150 because, if we can, we want to avoid moving such as assignments and variable
2151 declarations. This is done under the assumption that, if possible, avoiding
2152 selections containing unfixes will make the code moved a little cleaner.
2153
2154 \item The second criterion that is evaluated is whether a selection contains
2155 multiple possible targets or not. If selection \m{A} has only one possible
2156 target, and selection \m{B} has multiple, selection \m{A} is favored. If
2157 both selections have multiple possible targets, they are considered equal
2158 with respect to this criterion. The rationale for this heuristic is that we
2159 would prefer not to introduce new couplings between classes when performing
2160 the \ExtractAndMoveMethod refactoring.
9503a520
EK
2161
2162 \item When evaluating this criterion, this is with the knowledge that
01d46361
EK
2163 selection \m{A} and \m{B} both have one possible target, or multiple
2164 possible targets. Then, if the move target candidate of selection \m{A} has
2165 a higher reference count than the target candidate of selection \m{B},
2166 selection \m{A} is favored. The reason for this is that we would like to
2167 move the selection that gets rid of the most references to another class.
9503a520
EK
2168
2169 \item The last criterion is that if the frequencies of the targets chosen for
2170 both selections are equal, the selection with the target that is part of the
2171 prefix with highest number of segments is favored. This is done to favor
2172 indirection.
2173
2174\end{enumerate}
2175
2176If none of the above mentioned criteria favors one selection over another, the
2177selections are considered to be equally good candidates for the
2178\ExtractAndMoveMethod refactoring.
0cc6a67d 2179
01d46361
EK
2180\section{Concluding the example}
2181For choosing one of the remaining selections, we need to order our candidates
2182after the criteria in the previous section. Below we have the candidates ordered
2183in descending order, with the ``best'' candidate first:
2184
2185\begin{multicols}{2}
2186\begin{enumerate}
2187 \item $((16,17), \texttt{b.a}, f(2))$
2188 \item $((11,12), \texttt{a}, f(2))$
2189 \item $((16), \texttt{b.a}, f(1))$
2190 \item $((17), \texttt{b.a}, f(1))$
2191
2192 % With unfixes:
2193 % Many possible targets
2194 \item $((11,21), \texttt{a}, f(3))$
2195 \item $((5,21), \texttt{b.a}, f(2))$
2196 \item $((12,21), \texttt{b.a}, f(2))$
2197 \item $((14,21), \texttt{b.a}, f(2))$
2198
2199\end{enumerate}
2200\end{multicols}
2201
2202\begin{comment}
22035 if (bool) {
22046 a.foo();
22057 a = new A();
22068 a.bar();
22079 }
220810
220911 a.foo();
221012 a.bar();
221113
221214 switch (val) {
221315 case 1:
221416 b.a.foo();
221517 b.a.bar();
221618 break;
221719 default:
221820 a.foo();
221921 }
2220\end{comment}
2221
9db7f4cf
EK
2222The candidates ordered 5-8 all have unfixes in them, therefore they are ordered
2223last. None of the candidates ordered 1-4 have multiple possible targets. The
2224only interesting discussion is now why $(16,17)$ was favored over $(11,12)$.
2225This is because the prefix \code{b.a} enclosing the move target of selection
2226$(16,17)$ has one more segment than the prefix \code{a} of $(11,12)$.
2227
2228The selection is now extracted into a new method \method{gen\_123} and then
2229moved to class \type{B}, since that is the type of the variable \var{b} that is
2230the target from the chosen refactoring candidate. The name of the method has a
2231randomly generated suffix. In the refactoring implementation, the extracted
2232methods follow the pattern \code{generated\_<long>}, where \code{<long>} is a
2233pseudo-random long value. This is shortened here to make the example readable.
e36eade0 2234The result after the refactoring is shown in \myref{lst:grandExampleResult}.
01d46361
EK
2235
2236\begin{listing}[htb]
2237 \begin{multicols}{2}
2238 \begin{minted}[linenos]{java}
2239class C {
9db7f4cf
EK
2240 A a; B b; boolean bool;
2241
2242 void method(int val) {
2243 if (bool) {
2244 a.foo();
2245 a = new A();
2246 a.bar();
2247 }
2248
2249 a.foo();
2250 a.bar();
2251
2252 switch (val) {
2253 case 1:
2254 b.gen_123(this);
2255 break;
2256 default:
2257 a.foo();
01d46361 2258 }
9db7f4cf 2259 }
01d46361
EK
2260}
2261\end{minted}
2262
2263\columnbreak
2264
2265 \begin{minted}[]{java}
2266public class B {
9db7f4cf 2267 A a;
01d46361 2268
9db7f4cf
EK
2269 public void gen_123(C c) {
2270 a.foo();
2271 a.bar();
2272 }
01d46361
EK
2273}
2274\end{minted}
2275
2276 \end{multicols}
9db7f4cf
EK
2277 \caption{The result after refactoring the class \type{C} of
2278 \myref{lst:grandExample} with the \ExtractAndMoveMethod refactoring with
2279 $((16,17), \texttt{b.a}, f(2))$ as input.}
01d46361
EK
2280\label{lst:grandExampleResult}
2281\end{listing}
2282
b851f7df
EK
2283\chapter{Refactorings in Eclipse JDT: Design and
2284Shortcomings}\label{ch:jdt_refactorings}
5837a41f
EK
2285
2286This chapter will deal with some of the design behind refactoring support in
b4d90424
EK
2287\name{Eclipse}, and the JDT in specific. After which it will follow a section
2288about shortcomings of the refactoring API in terms of composition of
2289refactorings.
055dca93 2290
b0e80574 2291\section{Design}
fe0a4c48 2292The refactoring world of \name{Eclipse} can in general be separated into two parts: The
b289552b 2293language independent part and the part written for a specific programming
07e173d4
EK
2294language -- the language that is the target of the supported refactorings.
2295\todo{What about the language specific part?}
f041551b
EK
2296
2297\subsection{The Language Toolkit}
1326eec6
EK
2298The Language Toolkit\footnote{The content of this section is a mixture of
2299 written material from
2300 \url{https://www.eclipse.org/articles/Article-LTK/ltk.html} and
2301 \url{http://www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html},
2302the LTK source code and my own memory.}, or LTK for short, is the framework that
fe0a4c48 2303is used to implement refactorings in \name{Eclipse}. It is language independent and
1326eec6
EK
2304provides the abstractions of a refactoring and the change it generates, in the
2305form of the classes \typewithref{org.eclipse.ltk.core.refactoring}{Refactoring}
2306and \typewithref{org.eclipse.ltk.core.refactoring}{Change}.
2307
2308There are also parts of the LTK that is concerned with user interaction, but
2309they will not be discussed here, since they are of little value to us and our
2310use of the framework. We are primarily interested in the parts that can be
2311automated.
f041551b
EK
2312
2313\subsubsection{The Refactoring Class}
2314The abstract class \type{Refactoring} is the core of the LTK framework. Every
2315refactoring that is going to be supported by the LTK have to end up creating an
2316instance of one of its subclasses. The main responsibilities of subclasses of
2317\type{Refactoring} is to implement template methods for condition checking
2318(\methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{checkInitialConditions}
2319and
2320\methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{checkFinalConditions}),
2321in addition to the
2322\methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{createChange}
07e173d4
EK
2323method that creates and returns an instance of the \type{Change} class.
2324
2325If the refactoring shall support that others participate in it when it is
2326executed, the refactoring has to be a processor-based
2327refactoring\typeref{org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring}.
2328It then delegates to its given
2329\typewithref{org.eclipse.ltk.core.refactoring.participants}{RefactoringProcessor}
1326eec6
EK
2330for condition checking and change creation. Participating in a refactoring can
2331be useful in cases where the changes done to programming source code affects
2332other related resources in the workspace. This can be names or paths in
2333configuration files, or maybe one would like to perform additional logging of
2334changes done in the workspace.
f041551b
EK
2335
2336\subsubsection{The Change Class}
07e173d4
EK
2337This class is the base class for objects that is responsible for performing the
2338actual workspace transformations in a refactoring. The main responsibilities for
2339its subclasses is to implement the
2340\methodwithref{org.eclipse.ltk.core.refactoring.Change}{perform} and
2341\methodwithref{org.eclipse.ltk.core.refactoring.Change}{isValid} methods. The
2342\method{isValid} method verifies that the change object is valid and thus can be
2343executed by calling its \method{perform} method. The \method{perform} method
2344performs the desired change and returns an undo change that can be executed to
2345reverse the effect of the transformation done by its originating change object.
2346
61420ef7 2347\subsubsection{Executing a Refactoring}\label{executing_refactoring}
07e173d4
EK
2348The life cycle of a refactoring generally follows two steps after creation:
2349condition checking and change creation. By letting the refactoring object be
2350handled by a
2351\typewithref{org.eclipse.ltk.core.refactoring}{CheckConditionsOperation} that
2352in turn is handled by a
2353\typewithref{org.eclipse.ltk.core.refactoring}{CreateChangeOperation}, it is
2354assured that the change creation process is managed in a proper manner.
2355
2356The actual execution of a change object has to follow a detailed life cycle.
2357This life cycle is honored if the \type{CreateChangeOperation} is handled by a
2358\typewithref{org.eclipse.ltk.core.refactoring}{PerformChangeOperation}. If also
2359an undo manager\typeref{org.eclipse.ltk.core.refactoring.IUndoManager} is set
2360for the \type{PerformChangeOperation}, the undo change is added into the undo
2361history.
055dca93 2362
b0e80574 2363\section{Shortcomings}
80663734 2364This section is introduced naturally with a conclusion: The JDT refactoring
5837a41f
EK
2365implementation does not facilitate composition of refactorings.
2366\todo{refine}This section will try to explain why, and also identify other
2367shortcomings of both the usability and the readability of the JDT refactoring
2368source code.
80663734
EK
2369
2370I will begin at the end and work my way toward the composition part of this
2371section.
2372
5837a41f 2373\subsection{Absence of Generics in Eclipse Source Code}
80663734 2374This section is not only concerning the JDT refactoring API, but also large
fe0a4c48 2375quantities of the \name{Eclipse} source code. The code shows a striking absence of the
80663734 2376Java language feature of generics. It is hard to read a class' interface when
5837a41f
EK
2377methods return objects or takes parameters of raw types such as \type{List} or
2378\type{Map}. This sometimes results in having to read a lot of source code to
2379understand what is going on, instead of relying on the available interfaces. In
2380addition, it results in a lot of ugly code, making the use of typecasting more
2381of a rule than an exception.
2382
2383\subsection{Composite Refactorings Will Not Appear as Atomic Actions}
2384
2385\subsubsection{Missing Flexibility from JDT Refactorings}
2386The JDT refactorings are not made with composition of refactorings in mind. When
2387a JDT refactoring is executed, it assumes that all conditions for it to be
1326eec6 2388applied successfully can be found by reading source files that have been
5837a41f
EK
2389persisted to disk. They can only operate on the actual source material, and not
2390(in-memory) copies thereof. This constitutes a major disadvantage when trying to
1326eec6
EK
2391compose refactorings, since if an exception occurs in the middle of a sequence
2392of refactorings, it can leave the project in a state where the composite
2393refactoring was only partially executed. It makes it hard to discard the changes
5837a41f
EK
2394done without monitoring and consulting the undo manager, an approach that is not
2395bullet proof.
2396
2397\subsubsection{Broken Undo History}
2398When designing a composed refactoring that is to be performed as a sequence of
2399refactorings, you would like it to appear as a single change to the workspace.
2400This implies that you would also like to be able to undo all the changes done by
2401the refactoring in a single step. This is not the way it appears when a sequence
2402of JDT refactorings is executed. It leaves the undo history filled up with
2403individual undo actions corresponding to every single JDT refactoring in the
fe0a4c48 2404sequence. This problem is not trivial to handle in \name{Eclipse}
e123ab03 2405\see{hacking_undo_history}.
5837a41f 2406
80663734 2407
a7514fbd 2408
b0e80574
EK
2409\chapter{Composite Refactorings in Eclipse}
2410
2411\section{A Simple Ad Hoc Model}
fe0a4c48 2412As pointed out in \myref{ch:jdt_refactorings}, the \name{Eclipse} JDT refactoring model
8b6b22c8
EK
2413is not very well suited for making composite refactorings. Therefore a simple
2414model using changer objects (of type \type{RefaktorChanger}) is used as an
fe0a4c48 2415abstraction layer on top of the existing \name{Eclipse} refactorings, instead of
50954fde
EK
2416extending the \typewithref{org.eclipse.ltk.core.refactoring}{Refactoring} class.
2417
2418The use of an additional abstraction layer is a deliberate choice. It is due to
2419the problem of creating a composite
2420\typewithref{org.eclipse.ltk.core.refactoring}{Change} that can handle text
2421changes that interfere with each other. Thus, a \type{RefaktorChanger} may, or
2422may not, take advantage of one or more existing refactorings, but it is always
2423intended to make a change to the workspace.
2424
2425\subsection{A typical \type{RefaktorChanger}}
2426The typical refaktor changer class has two responsibilities, checking
2427preconditions and executing the requested changes. This is not too different
2428from the responsibilities of an LTK refactoring, with the distinction that a
2429refaktor changer also executes the change, while an LTK refactoring is only
2430responsible for creating the object that can later be used to do the job.
2431
2432Checking of preconditions is typically done by an
2433\typewithref{no.uio.ifi.refaktor.analyze.analyzers}{Analyzer}. If the
2434preconditions validate, the upcoming changes are executed by an
2435\typewithref{no.uio.ifi.refaktor.change.executors}{Executor}.
b0e80574
EK
2436
2437\section{The Extract and Move Method Refactoring}
61420ef7
EK
2438%The Extract and Move Method Refactoring is implemented mainly using these
2439%classes:
2440%\begin{itemize}
2441% \item \type{ExtractAndMoveMethodChanger}
2442% \item \type{ExtractAndMoveMethodPrefixesExtractor}
2443% \item \type{Prefix}
2444% \item \type{PrefixSet}
2445%\end{itemize}
2446
2447\subsection{The Building Blocks}
2448This is a composite refactoring, and hence is built up using several primitive
b5c7bb1b
EK
2449refactorings. These basic building blocks are, as its name implies, the
2450\ExtractMethod refactoring\citing{refactoring} and the \MoveMethod
fe0a4c48 2451refactoring\citing{refactoring}. In \name{Eclipse}, the implementations of these
b5c7bb1b 2452refactorings are found in the classes
61420ef7
EK
2453\typewithref{org.eclipse.jdt.internal.corext.refactoring.code}{ExtractMethodRefactoring}
2454and
2455\typewithref{org.eclipse.jdt.internal.corext.refactoring.structure}{MoveInstanceMethodProcessor},
2456where the last class is designed to be used together with the processor-based
2457\typewithref{org.eclipse.ltk.core.refactoring.participants}{MoveRefactoring}.
2458
2459\subsubsection{The ExtractMethodRefactoring Class}
2460This class is quite simple in its use. The only parameters it requires for
2461construction is a compilation
2462unit\typeref{org.eclipse.jdt.core.ICompilationUnit}, the offset into the source
2463code where the extraction shall start, and the length of the source to be
2464extracted. Then you have to set the method name for the new method together with
50954fde 2465its visibility and some not so interesting parameters.
61420ef7
EK
2466
2467\subsubsection{The MoveInstanceMethodProcessor Class}
fe0a4c48
EK
2468For the \refa{Move Method}, the processor requires a little more advanced input than
2469the class for the \refa{Extract Method}. For construction it requires a method
50954fde
EK
2470handle\typeref{org.eclipse.jdt.core.IMethod} for the method that is to be moved.
2471Then the target for the move have to be supplied as the variable binding from a
2472chosen variable declaration. In addition to this, one have to set some
2473parameters regarding setters/getters, as well as delegation.
61420ef7 2474
50954fde
EK
2475To make a working refactoring from the processor, one have to create a
2476\type{MoveRefactoring} with it.
b0e80574 2477
356782a0 2478\subsection{The ExtractAndMoveMethodChanger}
50954fde 2479
61420ef7 2480The \typewithref{no.uio.ifi.refaktor.changers}{ExtractAndMoveMethodChanger}
50954fde
EK
2481class is a subclass of the class
2482\typewithref{no.uio.ifi.refaktor.changers}{RefaktorChanger}. It is responsible
2483for analyzing and finding the best target for, and also executing, a composition
fe0a4c48 2484of the \refa{Extract Method} and \refa{Move Method} refactorings. This particular changer is
50954fde
EK
2485the one of my changers that is closest to being a true LTK refactoring. It can
2486be reworked to be one if the problems with overlapping changes are resolved. The
2487changer requires a text selection and the name of the new method, or else a
2488method name will be generated. The selection has to be of the type
2489\typewithref{no.uio.ifi.refaktor.utils}{CompilationUnitTextSelection}. This
2490class is a custom extension to
2491\typewithref{org.eclipse.jface.text}{TextSelection}, that in addition to the
2492basic offset, length and similar methods, also carry an instance of the
2493underlying compilation unit handle for the selection.
2494
ae138b9d
EK
2495\subsubsection{The
2496 \type{ExtractAndMoveMethodAnalyzer}}\label{extractAndMoveMethodAnalyzer}
50954fde
EK
2497The analysis and precondition checking is done by the
2498\typewithref{no.uio.ifi.refaktor.analyze.analyzers}{ExtractAnd\-MoveMethodAnalyzer}.
2499First is check whether the selection is a valid selection or not, with respect
2500to statement boundaries and that it actually contains any selections. Then it
2501checks the legality of both extracting the selection and also moving it to
95c0f364
EK
2502another class. This checking of is performed by a range of checkers
2503\see{checkers}. If the selection is approved as legal, it is analyzed to find
2504the presumably best target to move the extracted method to.
50954fde
EK
2505
2506For finding the best suitable target the analyzer is using a
2507\typewithref{no.uio.ifi.refaktor.analyze.collectors}{PrefixesCollector} that
ae138b9d
EK
2508collects all the possible candidate targets for the refactoring. All the
2509non-candidates is found by an
50954fde 2510\typewithref{no.uio.ifi.refaktor.analyze.collectors}{UnfixesCollector} that
b8fce5af 2511collects all the targets that will give some kind of error if used. (For
3ab3e132 2512details about the property collectors, see \myref{propertyCollectors}.) All
b8fce5af 2513prefixes (and unfixes) are represented by a
a6415293
EK
2514\typewithref{no.uio.ifi.refaktor.extractors}{Prefix}, and they are collected
2515into sets of prefixes. The safe prefixes is found by subtracting from the set of
b8fce5af 2516candidate prefixes the prefixes that is enclosing any of the unfixes. A prefix
a6415293 2517is enclosing an unfix if the unfix is in the set of its sub-prefixes. As an
01d46361
EK
2518example, \code{``a.b''} is enclosing \code{``a''}, as is \code{``a''}. The safe
2519prefixes is unified in a \type{PrefixSet}. If a prefix has only one occurrence,
2520and is a simple expression, it is considered unsuitable as a move target. This
2521occurs in statements such as \code{``a.foo()''}. For such statements it bares no
2522meaning to extract and move them. It only generates an extra method and the
2523calling of it.
50954fde 2524
fbaa89ce
EK
2525The most suitable target for the refactoring is found by finding the prefix with
2526the most occurrences. If two prefixes have the same occurrence count, but they
01d46361 2527differ in the number of segments, the one with most segments is chosen.
fbaa89ce 2528
c8088eec
EK
2529\subsubsection{The
2530 \type{ExtractAndMoveMethodExecutor}}\label{extractAndMoveMethodExecutor}
50954fde
EK
2531If the analysis finds a possible target for the composite refactoring, it is
2532executed by an
2533\typewithref{no.uio.ifi.refaktor.change.executors}{ExtractAndMoveMethodExecutor}.
2534It is composed of the two executors known as
2535\typewithref{no.uio.ifi.refaktor.change.executors}{ExtractMethodRefactoringExecutor}
2536and
2537\typewithref{no.uio.ifi.refaktor.change.executors}{MoveMethodRefactoringExecutor}.
2538The \type{ExtractAndMoveMethodExecutor} is responsible for gluing the two
3727b75b 2539together by feeding the \type{MoveMethod\-RefactoringExecutor} with the
222d172b 2540resources needed after executing the extract method refactoring.
50954fde
EK
2541
2542\subsubsection{The \type{ExtractMethodRefactoringExecutor}}
2543This executor is responsible for creating and executing an instance of the
2544\type{ExtractMethodRefactoring} class. It is also responsible for collecting
2545some post execution resources that can be used to find the method handle for the
2546extracted method, as well as information about its parameters, including the
2547variable they originated from.
2548
2549\subsubsection{The \type{MoveMethodRefactoringExecutor}}
2550This executor is responsible for creating and executing an instance of the
2551\type{MoveRefactoring}. The move refactoring is a processor-based refactoring,
fe0a4c48 2552and for the \refa{Move Method} refactoring it is the \type{MoveInstanceMethodProcessor}
50954fde
EK
2553that is used.
2554
2555The handle for the method to be moved is found on the basis of the information
fe0a4c48 2556gathered after the execution of the \refa{Extract Method} refactoring. The only
50954fde
EK
2557information the \type{ExtractMethodRefactoring} is sharing after its execution,
2558regarding find the method handle, is the textual representation of the new
2559method signature. Therefore it must be parsed, the strings for types of the
2560parameters must be found and translated to a form that can be used to look up
2561the method handle from its type handle. They have to be on the unresolved
2562form.\todo{Elaborate?} The name for the type is found from the original
2563selection, since an extracted method must end up in the same type as the
2564originating method.
2565
fe0a4c48 2566When analyzing a selection prior to performing the \refa{Extract Method} refactoring, a
50954fde
EK
2567target is chosen. It has to be a variable binding, so it is either a field or a
2568local variable/parameter. If the target is a field, it can be used with the
2569\type{MoveInstanceMethodProcessor} as it is, since the extracted method still is
2570in its scope. But if the target is local to the originating method, the target
2571that is to be used for the processor must be among its parameters. Thus the
2572target must be found among the extracted method's parameters. This is done by
2573finding the parameter information object that corresponds to the parameter that
2574was declared on basis of the original target's variable when the method was
2575extracted. (The extracted method must take one such parameter for each local
2576variable that is declared outside the selection that is extracted.) To match the
2577original target with the correct parameter information object, the key for the
2578information object is compared to the key from the original target's binding.
2579The source code must then be parsed to find the method declaration for the
2580extracted method. The new target must be found by searching through the
2581parameters of the declaration and choose the one that has the same type as the
2582old binding from the parameter information object, as well as the same name that
2583is provided by the parameter information object.
2584
2585
356782a0
EK
2586\subsection{The
2587SearchBasedExtractAndMoveMethodChanger}\label{searchBasedExtractAndMoveMethodChanger}
c8088eec
EK
2588The
2589\typewithref{no.uio.ifi.refaktor.change.changers}{SearchBasedExtractAndMoveMethodChanger}
2590is a changer whose purpose is to automatically analyze a method, and execute the
2591\ExtractAndMoveMethod refactoring on it if it is a suitable candidate for the
2592refactoring.
2593
2594First, the \typewithref{no.uio.ifi.refaktor.analyze.analyzers}{SearchBasedExtractAndMoveMethodAnalyzer} is used
2595to analyze the method. If the method is found to be a candidate, the result from
2596the analysis is fed to the \type{ExtractAndMoveMethodExecutor}, whose job is to
2597execute the refactoring \see{extractAndMoveMethodExecutor}.
2598
2599\subsubsection{The SearchBasedExtractAndMoveMethodAnalyzer}
2600This analyzer is responsible for analyzing all the possible text selections of a
2601method and then choose the best result out of the analysis results that is, by
2602the analyzer, considered to be the potential candidates for the Extract and Move
2603Method refactoring.
2604
2605Before the analyzer is able to work with the text selections of a method, it
2606needs to generate them. To do this, it parses the method to obtain a
2607\type{MethodDeclaration} for it \see{astEclipse}. Then there is a statement
2608lists creator that creates statements lists of the different groups of
2609statements in the body of the method declaration. A text selections generator
2610generates text selections of all the statement lists for the analyzer to work
2611with.
2612
2613\paragraph{The statement lists creator}
b851f7df
EK
2614is responsible for generating lists of statements for all the possible nesting
2615levels of statements in the method. The statement lists creator is implemented
2616as an AST visitor \see{astVisitor}. It generates lists of statements by visiting
2617all the blocks in the method declaration and stores their statements in a
2618collection of statement lists. In addition, it visits all of the other
2619statements that can have a statement as a child, such as the different control
2620structures and the labeled statement.
c8088eec
EK
2621
2622The switch statement is the only kind of statement that is not straight forward
2623to obtain the child statements from. It stores all of its children in a flat
2624list. Its switch case statements are included in this list. This means that
2625there are potential statement lists between all of these case statements. The
2626list of statements from a switch statement is therefore traversed, and the
2627statements between the case statements are grouped as separate lists.
2628
44005fe3
EK
2629The highlighted part of \myref{lst:grandExample} shows an example of how the
2630statement lists creator would separate a method body into lists of statements.
c8088eec
EK
2631
2632\paragraph{The text selections generator} generates text selections for each
b851f7df
EK
2633list of statements from the statement lists creator. The generator generates a
2634text selection for every sub-sequence of statements in a list. For a sequence of
2635statements, the first statement and the last statement span out a text
2636selection.
c8088eec
EK
2637
2638In practice, the text selections are calculated by only one traversal of the
2639statement list. There is a set of generated text selections. For each statement,
2640there is created a temporary set of selections, in addition to a text selection
2641based on the offset and length of the statement. This text selection is added to
2642the temporary set. Then the new selection is added with every selection from the
2643set of generated text selections. These new selections are added to the
2644temporary set. Then the temporary set of selections is added to the set of
2645generated text selections. The result of adding two text selections is a new
2646text selection spanned out by the two addends.
2647
53be7239 2648\begin{comment}
0fa64de5
EK
2649\begin{listing}[h]
2650\def\charwidth{5.7pt}
2651\def\indent{4*\charwidth}
2652\def\lineheight{\baselineskip}
2653\def\mintedtop{\lineheight}
2654
2655\begin{tikzpicture}[overlay, yscale=-1]
2656 \tikzstyle{overlaybox}=[fill=lightgray,opacity=0.2]
2657
2658 \draw[overlaybox] (2*\charwidth,\mintedtop) rectangle
2659 +(18*\charwidth,\lineheight);
2660
2661 \draw[overlaybox] (2*\charwidth,\mintedtop+\lineheight) rectangle
2662 +(18*\charwidth,\lineheight);
2663
2664 \draw[overlaybox] (2*\charwidth,\mintedtop+3*\lineheight) rectangle
2665 +(18*\charwidth,\lineheight);
2666
2667 \draw[overlaybox] (\indent-3*\charwidth,\mintedtop) rectangle
2668 +(20*\charwidth,2*\lineheight);
2669
2670 \draw[overlaybox] (3*\charwidth,\mintedtop+\lineheight) rectangle
2671 +(16*\charwidth,3*\lineheight);
2672
2673 \draw[overlaybox] (\indent,\mintedtop) rectangle
2674 +(14*\charwidth,4*\lineheight);
2675\end{tikzpicture}
2676\begin{minted}{java}
2677 statement one;
2678 statement two;
2679 ...
2680 statement k;
2681\end{minted}
2682\caption{Example of how the text selections generator would generate text
2683 selections based on a lists of statements. Each highlighted rectangle
2684represents a text selection.}
2685\label{lst:textSelectionsExample}
2686\end{listing}
021508ad
EK
2687\todoin{fix \myref{lst:textSelectionsExample}? Text only? All
2688sub-sequences\ldots}
53be7239 2689\end{comment}
0fa64de5 2690
ae138b9d
EK
2691\paragraph{Finding the candidate} for the refactoring is done by analyzing all
2692the generated text selection with the \type{ExtractAndMoveMethodAnalyzer}
2693\see{extractAndMoveMethodAnalyzer}. If the analyzer generates a useful result,
2694an \type{ExtractAndMoveMethodCandidate} is created from it, that is kept in a
2695list of potential candidates. If no candidates are found, the
2696\type{NoTargetFoundException} is thrown.
2697
2698Since only one of the candidates can be chosen, the analyzer must sort out which
2699candidate to choose. The sorting is done by the static \method{sort} method of
2700\type{Collections}. The comparison in this sorting is done by an
2701\type{ExtractAndMoveMethodCandidateComparator}.
2702\todoin{Write about the
2703ExtractAndMoveMethodCandidateComparator/FavorNoUnfixesCandidateComparator}
2704
356782a0 2705
b0e80574 2706\subsection{The Prefix Class}
a6415293
EK
2707This class exists mainly for holding data about a prefix, such as the expression
2708that the prefix represents and the occurrence count of the prefix within a
2709selection. In addition to this, it has some functionality such as calculating
2710its sub-prefixes and intersecting it with another prefix. The definition of the
2711intersection between two prefixes is a prefix representing the longest common
2712expression between the two.
2713
b0e80574 2714\subsection{The PrefixSet Class}
a6415293
EK
2715A prefix set holds elements of type \type{Prefix}. It is implemented with the
2716help of a \typewithref{java.util}{HashMap} and contains some typical set
2717operations, but it does not implement the \typewithref{java.util}{Set}
2718interface, since the prefix set does not need all of the functionality a
2719\type{Set} requires to be implemented. In addition It needs some other
2720functionality not found in the \type{Set} interface. So due to the relatively
2721limited use of prefix sets, and that it almost always needs to be referenced as
2722such, and not a \type{Set<Prefix>}, it remains as an ad hoc solution to a
2723concrete problem.
2724
2725There are two ways adding prefixes to a \type{PrefixSet}. The first is through
2726its \method{add} method. This works like one would expect from a set. It adds
2727the prefix to the set if it does not already contain the prefix. The other way
2728is to \emph{register} the prefix with the set. When registering a prefix, if the
2729set does not contain the prefix, it is just added. If the set contains the
2730prefix, its count gets incremented. This is how the occurrence count is handled.
2731
2732The prefix set also computes the set of prefixes that is not enclosing any
2733prefixes of another set. This is kind of a set difference operation only for
2734enclosing prefixes.
b0e80574 2735
5837a41f
EK
2736\subsection{Hacking the Refactoring Undo
2737History}\label{hacking_undo_history}
a6415293 2738\todoin{Where to put this section?}
8fae7b44
EK
2739
2740As an attempt to make multiple subsequent changes to the workspace appear as a
2741single action (i.e. make the undo changes appear as such), I tried to alter
2742the undo changes\typeref{org.eclipse.ltk.core.refactoring.Change} in the history
2743of the refactorings.
2744
2745My first impulse was to remove the, in this case, last two undo changes from the
f041551b 2746undo manager\typeref{org.eclipse.ltk.core.refactoring.IUndoManager} for the
fe0a4c48 2747\name{Eclipse} refactorings, and then add them to a composite
8fae7b44
EK
2748change\typeref{org.eclipse.ltk.core.refactoring.CompositeChange} that could be
2749added back to the manager. The interface of the undo manager does not offer a
2750way to remove/pop the last added undo change, so a possible solution could be to
4cb06723
EK
2751decorate\citing{designPatterns} the undo manager, to intercept and collect the
2752undo changes before delegating to the \method{addUndo}
f041551b 2753method\methodref{org.eclipse.ltk.core.refactoring.IUndoManager}{addUndo} of the
8fae7b44
EK
2754manager. Instead of giving it the intended undo change, a null change could be
2755given to prevent it from making any changes if run. Then one could let the
2756collected undo changes form a composite change to be added to the manager.
2757
2758There is a technical challenge with this approach, and it relates to the undo
2759manager, and the concrete implementation
94fc7e71
EK
2760\typewithref{org.eclipse.ltk.internal.core.refactoring}{UndoManager2}. This
2761implementation is designed in a way that it is not possible to just add an undo
2762change, you have to do it in the context of an active
8fae7b44
EK
2763operation\typeref{org.eclipse.core.commands.operations.TriggeredOperations}.
2764One could imagine that it might be possible to trick the undo manager into
2765believing that you are doing a real change, by executing a refactoring that is
2766returning a kind of null change that is returning our composite change of undo
94fc7e71 2767refactorings when it is performed. But this is not the way to go.
8fae7b44
EK
2768
2769Apart from the technical problems with this solution, there is a functional
2770problem: If it all had worked out as planned, this would leave the undo history
2771in a dirty state, with multiple empty undo operations corresponding to each of
2772the sequentially executed refactoring operations, followed by a composite undo
2773change corresponding to an empty change of the workspace for rounding of our
2774composite refactoring. The solution to this particular problem could be to
2775intercept the registration of the intermediate changes in the undo manager, and
2776only register the last empty change.
2777
2778Unfortunately, not everything works as desired with this solution. The grouping
2779of the undo changes into the composite change does not make the undo operation
2780appear as an atomic operation. The undo operation is still split up into
2781separate undo actions, corresponding to the change done by its originating
2782refactoring. And in addition, the undo actions has to be performed separate in
2783all the editors involved. This makes it no solution at all, but a step toward
2784something worse.
2785
2786There might be a solution to this problem, but it remains to be found. The
2787design of the refactoring undo management is partly to be blamed for this, as it
2788it is to complex to be easily manipulated.
2789
b0e80574 2790
0d7fbd88 2791
2f2080fb 2792
03674629 2793\chapter{Analyzing Source Code in Eclipse}
5308274d 2794
356782a0 2795\section{The Java model}\label{javaModel}
fe0a4c48 2796The Java model of \name{Eclipse} is its internal representation of a Java project. It
5308274d 2797is light-weight, and has only limited possibilities for manipulating source
fe0a4c48 2798code. It is typically used as a basis for the Package Explorer in \name{Eclipse}.
5308274d
EK
2799
2800The elements of the Java model is only handles to the underlying elements. This
2801means that the underlying element of a handle does not need to actually exist.
2802Hence the user of a handle must always check that it exist by calling the
2803\method{exists} method of the handle.
2804
8647eef7
EK
2805The handles with descriptions is listed in \myref{tab:javaModel}, while the
2806hierarchy of the Java Model is shown in \myref{fig:javaModel}.
4e468834 2807
8647eef7
EK
2808\begin{table}[htb]
2809 \caption{The elements of the Java Model\citing{vogelEclipseJDT2012}.}
2810 \label{tab:javaModel}
4e468834 2811 \centering
4e468834 2812 % sum must equal number of columns (3)
8647eef7
EK
2813 \begin{tabularx}{\textwidth}{@{} L{0.7} L{1.1} L{1.2} @{}}
2814 \toprule
4e468834
EK
2815 \textbf{Project Element} & \textbf{Java Model element} &
2816 \textbf{Description} \\
8647eef7 2817 \midrule
4e468834 2818 Java project & \type{IJavaProject} & The Java project which contains all other objects. \\
8647eef7 2819 \midrule
4e468834
EK
2820 Source folder /\linebreak[2] binary folder /\linebreak[3] external library &
2821 \type{IPackageFragmentRoot} & Hold source or binary files, can be a folder
2822 or a library (zip / jar file). \\
8647eef7 2823 \midrule
4e468834
EK
2824 Each package & \type{IPackageFragment} & Each package is below the
2825 \type{IPackageFragmentRoot}, sub-packages are not leaves of the package,
2826 they are listed directed under \type{IPackageFragmentRoot}. \\
8647eef7 2827 \midrule
4e468834
EK
2828 Java Source file & \type{ICompilationUnit} & The Source file is always below
2829 the package node. \\
8647eef7
EK
2830 \midrule
2831 Types / Fields /\linebreak[3] Methods & \type{IType} / \type{IField}
2832 /\linebreak[3] \type{IMethod} & Types, fields and methods. \\
2833 \bottomrule
4e468834 2834 \end{tabularx}
4e468834
EK
2835\end{table}
2836
4e468834 2837
5308274d
EK
2838\begin{figure}[h]
2839 \centering
2840 \begin{tikzpicture}[%
2841 grow via three points={one child at (0,-0.7) and
2842 two children at (0,-0.7) and (0,-1.4)},
2843 edge from parent path={(\tikzparentnode.south west)+(0.5,0) |-
2844 (\tikzchildnode.west)}]
2845 \tikzstyle{every node}=[draw=black,thick,anchor=west]
2846 \tikzstyle{selected}=[draw=red,fill=red!30]
2847 \tikzstyle{optional}=[dashed,fill=gray!50]
2848 \node {\type{IJavaProject}}
2849 child { node {\type{IPackageFragmentRoot}}
2850 child { node {\type{IPackageFragment}}
2851 child { node {\type{ICompilationUnit}}
2852 child { node {\type{IType}}
2853 child { node {\type{\{ IType \}*}}
2854 child { node {\type{\ldots}}}
2855 }
2856 child [missing] {}
2857 child { node {\type{\{ IField \}*}}}
2858 child { node {\type{IMethod}}
2859 child { node {\type{\{ IType \}*}}
2860 child { node {\type{\ldots}}}
2861 }
2862 }
2863 child [missing] {}
2864 child [missing] {}
2865 child { node {\type{\{ IMethod \}*}}}
2866 }
2867 child [missing] {}
2868 child [missing] {}
2869 child [missing] {}
2870 child [missing] {}
2871 child [missing] {}
2872 child [missing] {}
2873 child [missing] {}
2874 child { node {\type{\{ IType \}*}}}
2875 }
2876 child [missing] {}
2877 child [missing] {}
2878 child [missing] {}
2879 child [missing] {}
2880 child [missing] {}
2881 child [missing] {}
2882 child [missing] {}
2883 child [missing] {}
2884 child [missing] {}
2885 child { node {\type{\{ ICompilationUnit \}*}}}
2886 }
2887 child [missing] {}
2888 child [missing] {}
2889 child [missing] {}
2890 child [missing] {}
2891 child [missing] {}
2892 child [missing] {}
2893 child [missing] {}
2894 child [missing] {}
2895 child [missing] {}
2896 child [missing] {}
2897 child [missing] {}
2898 child { node {\type{\{ IPackageFragment \}*}}}
2899 }
2900 child [missing] {}
2901 child [missing] {}
2902 child [missing] {}
2903 child [missing] {}
2904 child [missing] {}
2905 child [missing] {}
2906 child [missing] {}
2907 child [missing] {}
2908 child [missing] {}
2909 child [missing] {}
2910 child [missing] {}
2911 child [missing] {}
2912 child [missing] {}
2913 child { node {\type{\{ IPackageFragmentRoot \}*}}}
2914 ;
2915 \end{tikzpicture}
fe0a4c48 2916 \caption{The Java model of \name{Eclipse}. ``\type{\{ SomeElement \}*}'' means
8647eef7 2917 ``\type{SomeElement} zero or more times``. For recursive structures,
5308274d
EK
2918 ``\type{\ldots}'' is used.}
2919 \label{fig:javaModel}
2920\end{figure}
2921
3ab3e132 2922\section{The Abstract Syntax Tree}
fe0a4c48 2923\name{Eclipse} is following the common paradigm of using an abstract syntax tree for
03674629
EK
2924source code analysis and manipulation.
2925
03674629
EK
2926When parsing program source code into something that can be used as a foundation
2927for analysis, the start of the process follows the same steps as in a compiler.
3ab3e132 2928This is all natural, because the way a compiler analyzes code is no different
03674629
EK
2929from how source manipulation programs would do it, except for some properties of
2930code that is analyzed in the parser, and that they may be differing in what
4e468834 2931kinds of properties they analyze. Thus the process of translation source code
03674629 2932into a structure that is suitable for analyzing, can be seen as a kind of
65e213db
EK
2933interrupted compilation process \see{fig:interruptedCompilationProcess}.
2934
2935\begin{figure}[h]
2936 \centering
2937 \tikzset{
c876d1a4 2938 base/.style={anchor=north, align=center, rectangle, minimum height=1.4cm},
65e213db 2939 basewithshadow/.style={base, drop shadow, fill=white},
c876d1a4
EK
2940 outlined/.style={basewithshadow, draw, rounded corners, minimum
2941 width=0.4cm},
2942 primary/.style={outlined, font=\bfseries},
65e213db 2943 dashedbox/.style={outlined, dashed},
62563950
EK
2944 arrowpath/.style={black, align=center, font=\small},
2945 processarrow/.style={arrowpath, ->, >=angle 90, shorten >=1pt},
65e213db 2946 }
62563950 2947 \begin{tikzpicture}[node distance=1.3cm and 3cm, scale=1, every
c876d1a4 2948 node/.style={transform shape}]
62563950
EK
2949 \node[base](AuxNode1){\small source code};
2950 \node[primary, right=of AuxNode1, xshift=-2.5cm](Scanner){Scanner};
c876d1a4 2951 \node[primary, right=of Scanner, xshift=0.5cm](Parser){Parser};
72e039dc
EK
2952 \node[dashedbox, below=of Parser](SemanticAnalyzer){Semantic\\Analyzer};
2953 \node[dashedbox, left=of SemanticAnalyzer](SourceCodeOptimizer){Source
2954 Code\\Optimizer};
2955 \node[dashedbox, below=of SourceCodeOptimizer
c876d1a4 2956 ](CodeGenerator){Code\\Generator};
72e039dc
EK
2957 \node[dashedbox, right=of CodeGenerator](TargetCodeOptimizer){Target
2958 Code\\Optimizer};
2959 \node[base, right=of TargetCodeOptimizer](AuxNode2){};
c876d1a4 2960
62563950
EK
2961 \draw[processarrow](AuxNode1) -- (Scanner);
2962
2963 \path[arrowpath] (Scanner) -- node [sloped](tokens){tokens}(Parser);
2964 \draw[processarrow](Scanner) -- (tokens) -- (Parser);
2965
2966 \path[arrowpath] (Parser) -- node (syntax){syntax
2967 tree}(SemanticAnalyzer);
2968 \draw[processarrow](Parser) -- (syntax) -- (SemanticAnalyzer);
2969
2970 \path[arrowpath] (SemanticAnalyzer) -- node
2971 [sloped](annotated){annotated\\tree}(SourceCodeOptimizer);
2972 \draw[processarrow, dashed](SemanticAnalyzer) -- (annotated) --
2973 (SourceCodeOptimizer);
2974
2975 \path[arrowpath] (SourceCodeOptimizer) -- node
2976 (intermediate){intermediate code}(CodeGenerator);
2977 \draw[processarrow, dashed](SourceCodeOptimizer) -- (intermediate) --
2978 (CodeGenerator);
2979
2980 \path[arrowpath] (CodeGenerator) -- node [sloped](target1){target
c876d1a4 2981 code}(TargetCodeOptimizer);
62563950
EK
2982 \draw[processarrow, dashed](CodeGenerator) -- (target1) --
2983 (TargetCodeOptimizer);
2984
2985 \path[arrowpath](TargetCodeOptimizer) -- node [sloped](target2){target
c876d1a4 2986 code}(AuxNode2);
62563950 2987 \draw[processarrow, dashed](TargetCodeOptimizer) -- (target2) (AuxNode2);
65e213db 2988 \end{tikzpicture}
72e039dc 2989 \caption{Interrupted compilation process. {\footnotesize (Full compilation
52da2102
EK
2990 process borrowed from \emph{Compiler construction: principles and practice}
2991 by Kenneth C. Louden\citing{louden1997}.)}}
65e213db
EK
2992 \label{fig:interruptedCompilationProcess}
2993\end{figure}
2994
03674629
EK
2995The process starts with a \emph{scanner}, or lexer. The job of the scanner is to
2996read the source code and divide it into tokens for the parser. Therefore, it is
2997also sometimes called a tokenizer. A token is a logical unit, defined in the
2998language specification, consisting of one or more consecutive characters. In
3ab3e132 2999the Java language the tokens can for instance be the \var{this} keyword, a curly
03674629 3000bracket \var{\{} or a \var{nameToken}. It is recognized by the scanner on the
3ab3e132 3001basis of something equivalent of a regular expression. This part of the process
03674629
EK
3002is often implemented with the use of a finite automata. In fact, it is common to
3003specify the tokens in regular expressions, that in turn is translated into a
3004finite automata lexer. This process can be automated.
3005
3ab3e132 3006The program component used to translate a stream of tokens into something
03674629
EK
3007meaningful, is called a parser. A parser is fed tokens from the scanner and
3008performs an analysis of the structure of a program. It verifies that the syntax
3009is correct according to the grammar rules of a language, that is usually
3010specified in a context-free grammar, and often in a variant of the
fe0a4c48 3011\name{Backus--Naur
03674629
EK
3012Form}\footnote{\url{https://en.wikipedia.org/wiki/Backus-Naur\_Form}}. The
3013result coming from the parser is in the form of an \emph{Abstract Syntax Tree},
3014AST for short. It is called \emph{abstract}, because the structure does not
3015contain all of the tokens produced by the scanner. It only contain logical
3016constructs, and because it forms a tree, all kinds of parentheses and brackets
3017are implicit in the structure. It is this AST that is used when performing the
3018semantic analysis of the code.
3019
3020As an example we can think of the expression \code{(5 + 7) * 2}. The root of
fe0a4c48 3021this tree would in \name{Eclipse} be an \type{InfixExpression} with the operator
d11bcf4d
EK
3022\var{TIMES}, and a left operand that is also an \type{InfixExpression} with the
3023operator \var{PLUS}. The left operand \type{InfixExpression}, has in turn a left
3024operand of type \type{NumberLiteral} with the value \var{``5''} and a right
3025operand \type{NumberLiteral} with the value \var{``7''}. The root will have a
3026right operand of type \type{NumberLiteral} and value \var{``2''}. The AST for
3027this expression is illustrated in \myref{fig:astInfixExpression}.
3028
3ab3e132
EK
3029Contrary to the Java Model, an abstract syntax tree is a heavy-weight
3030representation of source code. It contains information about properties like
3031type bindings for variables and variable bindings for names.
4e468834
EK
3032
3033
d11bcf4d
EK
3034\begin{figure}[h]
3035 \centering
a1d68d95 3036 \begin{tikzpicture}[scale=0.8]
894dce0d 3037 \tikzset{level distance=40pt}
a1d68d95
EK
3038 \tikzset{sibling distance=5pt}
3039 \tikzstyle{thescale}=[scale=0.8]
3040 \tikzset{every tree node/.style={align=center}}
d11bcf4d 3041 \tikzset{edge from parent/.append style={thick}}
a1d68d95
EK
3042 \tikzstyle{inode}=[rectangle,rounded corners,draw,fill=lightgray,drop
3043 shadow,align=center]
3044 \tikzset{every internal node/.style={inode}}
894dce0d 3045 \tikzset{every leaf node/.style={draw=none,fill=none}}
d11bcf4d 3046
894dce0d
EK
3047 \Tree [.\type{InfixExpression} [.\type{InfixExpression}
3048 [.\type{NumberLiteral} \var{``5''} ] [.\type{Operator} \var{PLUS} ]
3049 [.\type{NumberLiteral} \var{``7''} ] ]
d11bcf4d
EK
3050 [.\type{Operator} \var{TIMES} ]
3051 [.\type{NumberLiteral} \var{``2''} ]
3052 ]
3053 \end{tikzpicture}
894dce0d 3054 \caption{The abstract syntax tree for the expression \code{(5 + 7) * 2}.}
d11bcf4d
EK
3055 \label{fig:astInfixExpression}
3056\end{figure}
03674629 3057
c8088eec 3058\subsection{The AST in Eclipse}\label{astEclipse}
fe0a4c48 3059In \name{Eclipse}, every node in the AST is a child of the abstract superclass
03674629
EK
3060\typewithref{org.eclipse.jdt.core.dom}{ASTNode}. Every \type{ASTNode}, among a
3061lot of other things, provides information about its position and length in the
3062source code, as well as a reference to its parent and to the root of the tree.
3063
3064The root of the AST is always of type \type{CompilationUnit}. It is not the same
3065as an instance of an \type{ICompilationUnit}, which is the compilation unit
894dce0d 3066handle of the Java model. The children of a \type{CompilationUnit} is an
03674629
EK
3067optional \type{PackageDeclaration}, zero or more nodes of type
3068\type{ImportDecaration} and all its top-level type declarations that has node
3069types \type{AbstractTypeDeclaration}.
3070
3071An \type{AbstractType\-Declaration} can be one of the types
3072\type{AnnotationType\-Declaration}, \type{Enum\-Declaration} or
3073\type{Type\-Declaration}. The children of an \type{AbstractType\-Declaration}
3074must be a subtype of a \type{BodyDeclaration}. These subtypes are:
3075\type{AnnotationTypeMember\-Declaration}, \type{EnumConstant\-Declaration},
3076\type{Field\-Declaration}, \type{Initializer} and \type{Method\-Declaration}.
3077
3078Of the body declarations, the \type{Method\-Declaration} is the most interesting
3079one. Its children include lists of modifiers, type parameters, parameters and
3080exceptions. It has a return type node and a body node. The body, if present, is
3081of type \type{Block}. A \type{Block} is itself a \type{Statement}, and its
3082children is a list of \type{Statement} nodes.
3083
3084There are too many types of the abstract type \type{Statement} to list up, but
3085there exists a subtype of \type{Statement} for every statement type of Java, as
3086one would expect. This also applies to the abstract type \type{Expression}.
3087However, the expression \type{Name} is a little special, since it is both used
3088as an operand in compound expressions, as well as for names in type declarations
3089and such.
3090
fe0a4c48 3091There is an overview of some of the structure of an \name{Eclipse} AST in
94deee9e
EK
3092\myref{fig:astEclipse}.
3093
e8173df5
EK
3094\begin{figure}[h]
3095 \centering
5e5908eb 3096 \begin{tikzpicture}[scale=0.8]
0f918507
EK
3097 \tikzset{level distance=50pt}
3098 \tikzset{sibling distance=5pt}
5e5908eb 3099 \tikzstyle{thescale}=[scale=0.8]
e8173df5 3100 \tikzset{every tree node/.style={align=center}}
5e5908eb
EK
3101 \tikzset{edge from parent/.append style={thick}}
3102 \tikzstyle{inode}=[rectangle,rounded corners,draw,fill=lightgray,drop
3103 shadow,align=center]
3104 \tikzset{every internal node/.style={inode}}
e8173df5
EK
3105 \tikzset{every leaf node/.style={draw=none,fill=none}}
3106
e601ce99
EK
3107 \Tree [.\type{CompilationUnit} [.\type{[ PackageDeclaration ]} [.\type{Name} ]
3108 [.\type{\{ Annotation \}*} ] ]
3109 [.\type{\{ ImportDeclaration \}*} [.\type{Name} ] ]
0f918507 3110 [.\type{\{ AbstractTypeDeclaration \}+} [.\node(site){\type{\{
e601ce99 3111 BodyDeclaration \}*}}; ] [.\type{SimpleName} ] ]
e8173df5 3112 ]
e601ce99 3113 \begin{scope}[shift={(0.5,-6)}]
5e5908eb 3114 \node[inode,thescale](root){\type{MethodDeclaration}};
e601ce99 3115 \node[inode,thescale](modifiers) at (4.5,-5){\type{\{ IExtendedModifier \}*}
5e5908eb 3116 \\ {\footnotesize (Of type \type{Modifier} or \type{Annotation})}};
e601ce99 3117 \node[inode,thescale](typeParameters) at (-6,-3.5){\type{\{ TypeParameter
5e5908eb 3118 \}*}};
fbeec228 3119 \node[inode,thescale](parameters) at (-5,-5){\type{\{
5e5908eb 3120 SingleVariableDeclaration \}*} \\ {\footnotesize (Parameters)}};
e601ce99 3121 \node[inode,thescale](exceptions) at (5,-3){\type{\{ Name \}*} \\
5e5908eb 3122 {\footnotesize (Exceptions)}};
e601ce99 3123 \node[inode,thescale](return) at (-6.5,-2){\type{Type} \\ {\footnotesize
5e5908eb 3124 (Return type)}};
e601ce99
EK
3125 \begin{scope}[shift={(0,-5)}]
3126 \Tree [.\node(body){\type{[ Block ]} \\ {\footnotesize (Body)}};
3127 [.\type{\{ Statement \}*} [.\type{\{ Expression \}*} ]
3128 [.\type{\{ Statement \}*} [.\type{\ldots} ]]
3129 ]
3130 ]
3131 \end{scope}
0f918507 3132 \end{scope}
e601ce99
EK
3133 \draw[->,>=triangle 90,shorten >=1pt](root.east)..controls +(east:2) and
3134 +(south:1)..(site.south);
0f918507 3135
5e5908eb
EK
3136 \draw (root.south) -- (modifiers);
3137 \draw (root.south) -- (typeParameters);
3138 \draw (root.south) -- ($ (parameters.north) + (2,0) $);
3139 \draw (root.south) -- (exceptions);
3140 \draw (root.south) -- (return);
3141 \draw (root.south) -- (body);
3142
e8173df5 3143 \end{tikzpicture}
fe0a4c48 3144 \caption{The format of the abstract syntax tree in \name{Eclipse}.}
e8173df5
EK
3145 \label{fig:astEclipse}
3146\end{figure}
94deee9e 3147\todoin{Add more to the AST format tree? \myref{fig:astEclipse}}
a2868580 3148
b8fce5af 3149\section{The ASTVisitor}\label{astVisitor}
3ab3e132
EK
3150So far, the only thing that has been addressed is how the data that is going to
3151be the basis for our analysis is structured. Another aspect of it is how we are
3152going to traverse the AST to gather the information we need, so we can conclude
3153about the properties we are analysing. It is of course possible to start at the
3154top of the tree, and manually search through its nodes for the ones we are
3155looking for, but that is a bit inconvenient. To be able to efficiently utilize
3156such an approach, we would need to make our own framework for traversing the
3157tree and visiting only the types of nodes we are after. Luckily, this
fe0a4c48 3158functionality is already provided in \name{Eclipse}, by its
50976f51
EK
3159\typewithref{org.eclipse.jdt.core.dom}{ASTVisitor}.
3160
fe0a4c48
EK
3161The \name{Eclipse} AST, together with its \type{ASTVisitor}, follows the
3162\pattern{Visitor} pattern\citing{designPatterns}. The intent of this design
3163pattern is to facilitate extending the functionality of classes without touching
3164the classes themselves.
0a8ca90c 3165
fe0a4c48
EK
3166Let us say that there is a class hierarchy of elements. These elements all have
3167a method \method{accept(Visitor visitor)}. In its simplest form, the
0a8ca90c
EK
3168\method{accept} method just calls the \method{visit} method of the visitor with
3169itself as an argument, like this: \code{visitor.visit(this)}. For the visitors
3170to be able to extend the functionality of all the classes in the elements
3171hierarchy, each \type{Visitor} must have one visit method for each concrete
3172class in the hierarchy. Say the hierarchy consists of the concrete classes
3173\type{ConcreteElementA} and \type{ConcreteElementB}. Then each visitor must have
3174the (possibly empty) methods \method{visit(ConcreteElementA element)} and
3175\method{visit(ConcreteElementB element)}. This scenario is depicted in
3176\myref{fig:visitorPattern}.
50976f51 3177
3572a8ac
EK
3178\begin{figure}[h]
3179 \centering
3180 \tikzstyle{abstract}=[rectangle, draw=black, fill=white, drop shadow, text
3181 centered, anchor=north, text=black, text width=6cm, every one node
3182part/.style={align=center, font=\bfseries\itshape}]
3183 \tikzstyle{concrete}=[rectangle, draw=black, fill=white, drop shadow, text
3184 centered, anchor=north, text=black, text width=6cm]
3185 \tikzstyle{inheritarrow}=[->, >=open triangle 90, thick]
3186 \tikzstyle{commentarrow}=[->, >=angle 90, dashed]
3187 \tikzstyle{line}=[-, thick]
3188 \tikzset{every one node part/.style={align=center, font=\bfseries}}
3189 \tikzset{every second node part/.style={align=center, font=\ttfamily}}
3572a8ac
EK
3190
3191 \begin{tikzpicture}[node distance=1cm, scale=0.8, every node/.style={transform
3192 shape}]
3193 \node (Element) [abstract, rectangle split, rectangle split parts=2]
3194 {
3195 \nodepart{one}{Element}
3196 \nodepart{second}{+accept(visitor: Visitor)}
3197 };
3198 \node (AuxNode01) [text width=0, minimum height=2cm, below=of Element] {};
3199 \node (ConcreteElementA) [concrete, rectangle split, rectangle split
3200 parts=2, left=of AuxNode01]
3201 {
3202 \nodepart{one}{ConcreteElementA}
3203 \nodepart{second}{+accept(visitor: Visitor)}
3204 };
3205 \node (ConcreteElementB) [concrete, rectangle split, rectangle split
3206 parts=2, right=of AuxNode01]
3207 {
3208 \nodepart{one}{ConcreteElementB}
3209 \nodepart{second}{+accept(visitor: Visitor)}
3210 };
3211
3212 \node[comment, below=of ConcreteElementA] (CommentA) {visitor.visit(this)};
3213
3214 \node[comment, below=of ConcreteElementB] (CommentB) {visitor.visit(this)};
3215
3216 \node (AuxNodeX) [text width=0, minimum height=1cm, below=of AuxNode01] {};
3217
3218 \node (Visitor) [abstract, rectangle split, rectangle split parts=2,
3219 below=of AuxNodeX]
3220 {
3221 \nodepart{one}{Visitor}
3222 \nodepart{second}{+visit(ConcreteElementA)\\+visit(ConcreteElementB)}
3223 };
3224 \node (AuxNode02) [text width=0, minimum height=2cm, below=of Visitor] {};
3225 \node (ConcreteVisitor1) [concrete, rectangle split, rectangle split
3226 parts=2, left=of AuxNode02]
3227 {
3228 \nodepart{one}{ConcreteVisitor1}
3229 \nodepart{second}{+visit(ConcreteElementA)\\+visit(ConcreteElementB)}
3230 };
3231 \node (ConcreteVisitor2) [concrete, rectangle split, rectangle split
3232 parts=2, right=of AuxNode02]
3233 {
3234 \nodepart{one}{ConcreteVisitor2}
3235 \nodepart{second}{+visit(ConcreteElementA)\\+visit(ConcreteElementB)}
3236 };
3237
3238
3239 \draw[inheritarrow] (ConcreteElementA.north) -- ++(0,0.7) -|
3240 (Element.south);
3241 \draw[line] (ConcreteElementA.north) -- ++(0,0.7) -|
3242 (ConcreteElementB.north);
3243
3244 \draw[inheritarrow] (ConcreteVisitor1.north) -- ++(0,0.7) -|
3245 (Visitor.south);
3246 \draw[line] (ConcreteVisitor1.north) -- ++(0,0.7) -|
3247 (ConcreteVisitor2.north);
3248
3249 \draw[commentarrow] (CommentA.north) -- (ConcreteElementA.south);
3250 \draw[commentarrow] (CommentB.north) -- (ConcreteElementB.south);
3251
3252
3253 \end{tikzpicture}
3254 \caption{The Visitor Pattern.}
3255 \label{fig:visitorPattern}
3256\end{figure}
3257
0a8ca90c
EK
3258The use of the visitor pattern can be appropriate when the hierarchy of elements
3259is mostly stable, but the family of operations over its elements is constantly
fe0a4c48 3260growing. This is clearly the case for the \name{Eclipse} AST, since the hierarchy of
0a8ca90c
EK
3261type \type{ASTNode} is very stable, but the functionality of its elements is
3262extended every time someone needs to operate on the AST. Another aspect of the
fe0a4c48 3263\name{Eclipse} implementation is that it is a public API, and the visitor pattern is an
0a8ca90c
EK
3264easy way to provide access to the nodes in the tree.
3265
fe0a4c48 3266The version of the visitor pattern implemented for the AST nodes in \name{Eclipse} also
0a8ca90c
EK
3267provides an elegant way to traverse the tree. It does so by following the
3268convention that every node in the tree first let the visitor visit itself,
b3adff95
EK
3269before it also makes all its children accept the visitor. The children are only
3270visited if the visit method of their parent returns \var{true}. This pattern
3271then makes for a prefix traversal of the AST. If postfix traversal is desired,
3272the visitors also has \method{endVisit} methods for each node type, that is
3273called after the \method{visit} method for a node. In addition to these visit
3274methods, there are also the methods \method{preVisit(ASTNode)},
3275\method{postVisit(ASTNode)} and \method{preVisit2(ASTNode)}. The
3276\method{preVisit} method is called before the type-specific \method{visit}
3277method. The \method{postVisit} method is called after the type-specific
3278\method{endVisit}. The type specific \method{visit} is only called if
3279\method{preVisit2} returns \var{true}. Overriding the \method{preVisit2} is also
3280altering the behavior of \method{preVisit}, since the default implementation is
94c59647
EK
3281responsible for calling it.
3282
3283An example of a trivial \type{ASTVisitor} is shown in
3284\myref{lst:astVisitorExample}.
3285
3286\begin{listing}
3287\begin{minted}{java}
3288public class CollectNamesVisitor extends ASTVisitor {
3289 Collection<Name> names = new LinkedList<Name>();
3290
3291 @Override
3292 public boolean visit(QualifiedName node) {
3293 names.add(node);
3294 return false;
3295 }
3296
3297 @Override
3298 public boolean visit(SimpleName node) {
3299 names.add(node);
3300 return true;
3301 }
3302}
3303\end{minted}
3304\caption{An \type{ASTVisitor} that visits all the names in a subtree and adds
3305them to a collection, except those names that are children of any
3306\type{QualifiedName}.}
3307\label{lst:astVisitorExample}
3308\end{listing}
3309
b8fce5af
EK
3310\section{Property collectors}\label{propertyCollectors}
3311The prefixes and unfixes are found by property
3312collectors\typeref{no.uio.ifi.refaktor.extractors.collectors.PropertyCollector}.
3313A property collector is of the \type{ASTVisitor} type, and thus visits nodes of
3314type \type{ASTNode} of the abstract syntax tree \see{astVisitor}.
3315
3316\subsection{The PrefixesCollector}
3317The \typewithref{no.uio.ifi.refaktor.extractors.collectors}{PrefixesCollector}
ccd252c5 3318finds prefixes that makes up the basis for calculating move targets for the
fe0a4c48 3319\refa{Extract and Move Method} refactoring. It visits expression
b8fce5af
EK
3320statements\typeref{org.eclipse.jdt.core.dom.ExpressionStatement} and creates
3321prefixes from its expressions in the case of method invocations. The prefixes
3322found is registered with a prefix set, together with all its sub-prefixes.
3323
3324\subsection{The UnfixesCollector}\label{unfixes}
3325The \typewithref{no.uio.ifi.refaktor.extractors.collectors}{UnfixesCollector}
47c0bea8 3326finds unfixes within a selection.
5230243c 3327\todoin{Give more technical detail?}
b8fce5af 3328
b8fce5af 3329
0a8ca90c 3330
5195bf0c 3331\subsection{The ContainsReturnStatementCollector}
21506154 3332\todoin{Remove section?}
5195bf0c
EK
3333The
3334\typewithref{no.uio.ifi.refaktor.analyze.collectors}{ContainsReturnStatementCollector}
3335is a very simple property collector. It only visits the return statements within
3336a selection, and can report whether it encountered a return statement or not.
3337
b8d069e4
EK
3338\subsection{The LastStatementCollector}
3339The \typewithref{no.uio.ifi.refaktor.analyze.collectors}{LastStatementCollector}
3340collects the last statement of a selection. It does so by only visiting the top
3341level statements of the selection, and compares the textual end offset of each
3ab3e132 3342encountered statement with the end offset of the previous statement found.
b8d069e4 3343
95c0f364 3344\section{Checkers}\label{checkers}
d6f8e65a
EK
3345The checkers are a range of classes that checks that text selections complies
3346with certain criteria. All checkers operates under the assumption that the code
3347they check is free from compilation errors. If a
95c0f364
EK
3348\typewithref{no.uio.ifi.refaktor.analyze.analyzers}{Checker} fails, it throws a
3349\type{CheckerException}. The checkers are managed by the
3350\type{LegalStatementsChecker}, which does not, in fact, implement the
3351\type{Checker} interface. It does, however, run all the checkers registered with
3352it, and reports that all statements are considered legal if no
08cbba3b 3353\type{CheckerException} is thrown. Many of the checkers either extends the
f72f72f1 3354\type{PropertyCollector} or utilizes one or more property collectors to verify
3ab3e132 3355some criteria. The checkers registered with the \type{LegalStatementsChecker}
f72f72f1 3356are described next. They are run in the order presented below.
95c0f364 3357
a22915d0 3358\subsection{The CallToProtectedOrPackagePrivateMethodChecker}
21506154
EK
3359This checker is used to check that at selection does not contain a call to a
3360method that is protected or package-private. Such a method either has the access
3361modifier \code{protected} or it has no access modifier.
a22915d0 3362
21506154
EK
3363The workings of the \type{CallToProtectedOrPackagePrivateMethod\-Checker} is
3364very simple. It looks for calls to methods that are either protected or
3365package-private within the selection, and throws an
3366\type{IllegalExpressionFoundException} if one is found.
a22915d0 3367
1fceb439
EK
3368\subsection{The DoubleClassInstanceCreationChecker}
3369The \type{DoubleClassInstanceCreationChecker} checks that there are no double
3370class instance creations where the inner constructor call take and argument that
3371is built up using field references.
3372
3373The checker visits all nodes of type \type{ClassInstanceCreation} within a
3374selection. For all of these nodes, if its parent also is a class instance
3375creation, it accepts a visitor that throws a
e36eade0 3376\type{IllegalExpressionFoundException} if it encounters a name that is a field
1fceb439
EK
3377reference.
3378
2a4b8dea 3379\subsection{The InstantiationOfNonStaticInnerClassChecker}
c6102ec2
EK
3380The \type{InstantiationOfNonStaticInnerClassChecker} checks that selections
3381does not contain instantiations of non-static inner classes. The
58467004 3382\type{MoveInstanceMethodProcessor} in \name{Eclipse} does not handle such
c6102ec2
EK
3383instantiations gracefully when moving a method. This problem is also related to
3384bug\ldots \todoin{File Eclipse bug report}
2a4b8dea 3385
8d0caf4c 3386\subsection{The EnclosingInstanceReferenceChecker}
98b06ec2
EK
3387The purpose of this checker is to verify that the names in a text selection are
3388not referencing any enclosing instances. In theory, the underlying problem could
3389be solved in some situations, but our dependency on the
8d0caf4c
EK
3390\type{MoveInstanceMethodProcessor} prevents this.
3391
3392The
3393\typewithref{no.uio.ifi.refaktor.analyze.analyzers}{EnclosingInstanceReferenceChecker}
3394is a modified version of the
801ff00a 3395\typewithref{org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethod\-Processor}{EnclosingInstanceReferenceFinder}
8d0caf4c 3396from the \type{MoveInstanceMethodProcessor}. Wherever the
98b06ec2
EK
3397\type{EnclosingInstanceReferenceFinder} would create a fatal error status, the
3398checker will throw a \type{CheckerException}.
3399
3400The checker works by first finding all of the enclosing types of a selection.
3401Thereafter, it visits all the simple names of the selection to check that they
3402are not references to variables or methods declared in any of the enclosing
3403types. In addition, the checker visits \var{this}-expressions to verify that no
3404such expressions are qualified with any name.
8d0caf4c 3405
9cc2cd59 3406\subsection{The ReturnStatementsChecker}\label{returnStatementsChecker}
d59e3ab7
EK
3407The checker for return statements is meant to verify that a text selection is
3408consistent regarding return statements.
3409
3410If the selection is free from return statements, then the checker validates. So
3411this is the first thing the checker investigates.
d6f8e65a 3412
e36eade0 3413If the checker proceeds any further, it is because the selection contains one
d6f8e65a 3414or more return statements. The next test is therefore to check if the last
d59e3ab7
EK
3415statement of the selection ends in either a return or a throw statement. The
3416responsibility for checking that the last statement of the selection eventually
3417ends in a return or throw statement, is put on the
801ff00a 3418\type{LastStatementOfSelectionEndsInReturnOrThrowChecker}. For every node
d59e3ab7 3419visited, if the node is a statement, it does a test to see if the statement is a
801ff00a
EK
3420return, a throw or if it is an implicit return statement. If this is the case,
3421no further checking is done. This checking is done in the \code{preVisit2}
3422method \see{astVisitor}. If the node is not of a type that is being handled by
d59e3ab7 3423its type-specific visit method, the checker performs a simple test. If the node
801ff00a
EK
3424being visited is not the last statement of its parent that is also enclosed by
3425the selection, an \type{IllegalStatementFoundException} is thrown. This ensures
3426that all statements are taken care of, one way or the other. It also ensures
3427that the checker is conservative in the way it checks for legality of the
3428selection.
3429
3430To examine if a statement is an implicit return statement, the checker first
3431finds the last statement declared in its enclosing method. If this statement is
3432the same as the one under investigation, it is considered an implicit return
3433statement. If the statements are not the same, the checker does a search to see
d59e3ab7 3434if the statement examined is also the last statement of the method that can be
801ff00a
EK
3435reached. This includes the last statement of a block statement, a labeled
3436statement, a synchronized statement or a try statement, that in turn is the last
d59e3ab7
EK
3437statement enclosed by one of the statement types listed. This search goes
3438through all the parents of a statement until a statement is found that is not
3439one of the mentioned acceptable parent statements. If the search ends in a
3440method declaration, then the statement is considered to be the last reachable
3441statement of the method, and thus it is an implicit return statement.
3442
3443There are two kinds of statements that are handled explicitly: If-statements and
3444try-statements. Block, labeled and do-statements are handled by fall-through to
3445the other two.
3446
3447If-statements are handled explicitly by overriding their type-specific visit
3448method. If the then-part does not contain any return or throw statements an
3449\type{IllegalStatementFoundException} is thrown. If it does contain a return or
801ff00a 3450throw, its else-part is checked. If the else-part is non-existent, or it does
d59e3ab7
EK
3451not contain any return or throw statements an exception is thrown. If no
3452exception is thrown while visiting the if-statement, its children are visited.
801ff00a 3453
d59e3ab7 3454A try-statement is checked very similar to an if-statement. Its body must
801ff00a 3455contain a return or throw. The same applies to its catch clauses and finally
d59e3ab7 3456body. Failure to validate produces an \type{IllegalStatementFoundException}.
801ff00a
EK
3457
3458If the checker does not complain at any point, the selection is considered valid
3459with respect to return statements.
41cde50e
EK
3460
3461\subsection{The AmbiguousReturnValueChecker}
5230243c 3462This checker verifies that there are no ambiguous return values in a selection.
9cc2cd59 3463
5230243c 3464First, the checker needs to collect some data. Those data are the binding keys
9cc2cd59
EK
3465for all simple names that are assigned to within the selection, including
3466variable declarations, but excluding fields. The checker also collects whether
3467there exists a return statement in the selection or not. No further checks of
3468return statements are needed, since, at this point, the selection is already
3469checked for illegal return statements \see{returnStatementsChecker}.
3470
3471After the binding keys of the assignees are collected, the checker searches the
3472part of the enclosing method that is after the selection for references whose
3ab3e132
EK
3473binding keys are among the collected keys. If more than one unique referral is
3474found, or only one referral is found, but the selection also contains a return
3475statement, we have a situation with an ambiguous return value, and an exception
3476is thrown.
9cc2cd59
EK
3477
3478%\todoin{Explain why we do not need to consider variables assigned inside
3479%local/anonymous classes. (The referenced variables need to be final and so
3480%on\ldots)}
41cde50e
EK
3481
3482\subsection{The IllegalStatementsChecker}
3483This checker is designed to check for illegal statements.
3484
8fa89d14
EK
3485Notice that labels in break and continue statements needs some special
3486treatment. Since a label does not have any binding information, we have to
3487search upwards in the AST to find the \type{LabeledStatement} that corresponds
3488to the label from the break or continue statement, and check that it is
3489contained in the selection. If the break or continue statement does not have a
3490label attached to it, it is checked that its innermost enclosing loop or switch
3491statement (break statements only) also is contained in the selection.
08cbba3b 3492
8fa89d14 3493\todoin{Follow the development in the semantics section\ldots}
41cde50e 3494
58467004
EK
3495\chapter{Case Studies}
3496
3497In this chapter I am going to present a few case studies. This is done to give
e36eade0 3498an impression of how the search-based \ExtractAndMoveMethod refactoring
01d46361
EK
3499performs when giving it a larger project to take on. I will try to answer where
3500it lacks, in terms of completeness, as well as showing its effect on refactored
3501source code.
58467004
EK
3502
3503The first and primary case, is refactoring source code from the \name{Eclipse
3504JDT UI} project. The project is chosen because it is a real project, still in
3505development, with a large code base that is written by many different people
3506through several years. The code is installed in thousands of \name{Eclipse}
3507applications worldwide, and must be seen as a good representative for
3508professionally written Java source code. It is also the home for most of the JDT
3509refactoring code.
3510
3511For the second case, the \ExtractAndMoveMethod refactoring is fed the
3512\code{no.uio.ifi.refaktor} project. This is done as a variation of the
3513``dogfooding'' methodology, where you use your own tools to do your job, also
3514referred to as ``eating your own dog
3515food''\citing{harrisonDogfooding2006}.
3516
3517\section{The tools}
6fabec9b
EK
3518For conducting these experiments, three tools are used. Two of the ``tools''
3519both uses Eclipse as their platform. The first is our own tool,
58467004 3520written to be able to run the \ExtractAndMoveMethod refactoring as a batch
e36eade0 3521process, analyzing and refactoring many methods after each other. The second is
c9488804
EK
3522JUnit, that is used for running the projects own unit tests on the target code
3523both before and after it is refactored. The last tool that is used is a code
3524quality management tool, called \name{SonarQube}. It can be used to perform
3525different tasks for assuring code quality, but we are only going to take
3526advantage of one of its main features, namely Quality profiles.
58467004
EK
3527
3528A quality profile is used to define a set of coding rules that a project is
3529supposed to comply with. Failure to following these rules will be recorded as
3530so-called ``issues'', marked as having one of several degrees of severities,
3531ranging from ``info'' to ``blocker'', where the latter one is the most severe.
3532The measurements done for these case studies are therefore not presented as
3533fine-grained software metrics results, but rather as the number of issues for
6fabec9b
EK
3534each defined rule.
3535
bc7b5d67 3536In addition to the coding rules defined through quality profiles, \name{SonarQube}
6fabec9b
EK
3537calculates the complexity of source code. The metric that is used is cyclomatic
3538complexity, developed by Thomas J. McCabe in
35391976\citing{mccabeComplexity1976}. In this metric, functions have an initial
3540complexity of 1, and whenever the control flow of a function splits, the
3541complexity increases by
3542one\footnote{\url{http://docs.codehaus.org/display/SONAR/Metric+definitions}}.
bc7b5d67 3543\name{SonarQube} discriminates between functions and accessors. Accessors
6fabec9b
EK
3544are methods that are recognized as setters or getters. Accessors are not counted
3545in the complexity analysis.
3546
bc7b5d67
EK
3547\section{The \name{SonarQube} quality profile}
3548The quality profile that is used with \name{SonarQube} in these case studies has got
3549the name \name{IFI Refaktor Case Study} (version 6). The rules defined in the
3550profile are chosen because they are the available rules found in \name{SonarQube} that
3551measures complexity and coupling. Now follows a description of the rules in the
3552quality profile. The values that are set for these rules are listed in
6fabec9b
EK
3553\myref{tab:qualityProfile1}.
3554
3555\begin{description}
3556 \item[Avoid too complex class] is a rule that measures cyclomatic complexity
3557 for every statement in the body of a class, except for setters and getter.
bc7b5d67 3558 The threshold value set is its default value of 200.
6fabec9b
EK
3559
3560 \item[Classes should not be coupled to too many other classes ] is a rule that
3561 measures how many other classes a class depends upon. It does not count the
3562 dependencies of nested classes. It is meant to promote the Single
3563 Responsibility Principle. Although not explicitly stated, the rule's metric
3564 resembles the \metr{Coupling between object classes} (CBO) metric that is
3565 described by Chidamber and Kemerer in their article \tit{A Metrics Suite for
3566 Object Oriented Design}\citing{metricsSuite1994}. The max value for the rule
3567 is chosen on the background of an empirical study by Raed Shatnawi, that
3568 concludes that the number 9 is the most useful threshold for the CBO
98660ec0
EK
3569 metric\citing{shatnawiQuantitative2010}. This study is also performed on
3570 Eclipse source code, so this threshold value should be particularly well
3571 suited for the Eclipse JDT UI case in this chapter.
6fabec9b
EK
3572
3573 \item[Control flow statements \ldots{} should not be nested too deeply] is
3574 a rule that is meant to counter ``Spaghetti code''. It measures the nesting
3575 level of if, for, while, switch and try statements. The nesting levels start
bc7b5d67 3576 at 1. The max value set is its default value of 3.
6fabec9b
EK
3577
3578 \item[Methods should not be too complex] is a rule that measures cyclomatic
3579 complexity the same way as the ``Avoid too complex class'' rule. The max
3580 value used is 10, which ``seems like a reasonable, but not magical, upper
3581 limit``\citing{mccabeComplexity1976}.
3582
3583 \item[Methods should not have too many lines] is a rule that simply measures
bc7b5d67
EK
3584 the number of lines in methods. The threshold value of 20 is used for this
3585 metric. This is based on my own subjective opinions, as the default value of
3586 100 seems a bit too loose.
6fabec9b
EK
3587
3588 \item[NPath Complexity] is a rule that measures the number of possible
3589 execution paths through a function. The value used is the default value of
3590 200, that seems like a recognized threshold for this metric.
3591
3592 \item[Too many methods] is a rule that measures the number of methods in a
bc7b5d67 3593 class. The threshold value used is the default value of 10.
6fabec9b
EK
3594
3595\end{description}
3596
3597
3598\begin{table}[htb]
bc7b5d67 3599 \caption{The \name{IFI Refaktor Case Study} quality profile (version 6).}
6fabec9b
EK
3600 \label{tab:qualityProfile1}
3601 \centering
3602 \begin{tabularx}{\textwidth}{@{}>{\bfseries}L{1.5}R{0.5}@{}}
3603 \toprule
3604 \textbf{Rule} & \textbf{Max value} \\
3605 \midrule
3606 Avoid too complex class & 200 \\
3607 Classes should not be coupled to too many other classes (Single
3608 Responsibility Principle) & 9 \\
3609 Control flow statements \ldots{} should not be nested too deeply &
3610 3 \\
3611 Methods should not be too complex & 10 \\
3612 Methods should not have too many lines & 20 \\
3613 NPath Complexity & 200 \\
bc7b5d67 3614 Too many methods & 10 \\
6fabec9b
EK
3615
3616 \bottomrule
3617 \end{tabularx}
3618\end{table}
58467004 3619
bc7b5d67
EK
3620\section{The input}
3621A precondition for the source code that is going to be the target for a series
3622of \ExtractAndMoveMethod refactorings, is that it is organized as an Eclipse
3623project. It is also assumed that the code is free from compilation errors.
3624
3625\section{The experiment}
3626For a given project, the first job that is done, is to refactor its source code.
3627The refactoring batch job produces three things: The refactored project,
3628statistics gathered during the execution of the series of refactorings, and an
3629error log describing any errors happening during this execution. See
3630\myref{sec:benchmarking} for more information about how the refactorings are
3631performed.
3632
3633After the refactoring process is done, the before- and after-code is analyzed
3634with \name{SonarQube}. The analysis results are then stored in a database and
3635displayed through a \name{SonarQube} server with a web interface.\todoin{How
3636long are these results going to be publicly available?}
3637
3638The before- and after-code is also tested with their own unit tests. This is
3639done to discover any changes in the semantic behavior of the refactored code,
3640within the limits of these tests.
3641
58467004 3642\section{Case 1: The Eclipse JDT UI project}
98660ec0 3643This case is the ultimate test for our \ExtractAndMoveMethod refactoring. The
e36eade0 3644target source code is massive. With its over 300,000 lines of code and over
98660ec0 364525,000 methods, it is formidable task to perform automated changes on it. There
e36eade0 3646should be plenty of situations where things can go wrong, and, as we shall see
701c559a 3647later, they do.
98660ec0
EK
3648
3649I will start by presenting some statistics from the refactoring execution,
3650before I pick apart the \name{SonarQube} analysis and conclude by commenting on
701c559a
EK
3651the results from the unit tests. The configuration for the experiment is
3652specified in \myref{tab:configurationCase1}.
98660ec0 3653
701c559a
EK
3654\begin{table}[htb]
3655 \caption{Configuration for Case 1.}
3656 \label{tab:configurationCase1}
3657 \centering
3658 \begin{tabularx}{\textwidth}{@{}>{\bfseries}L{0.67}L{1.33}@{}}
3659 \toprule
3660 \spancols{2}{Benchmark data} \\
3661 \midrule
3662 Launch configuration & CaseStudy.launch \\
3663 Project & no.uio.ifi.refaktor.benchmark \\
3664 Repository & gitolite@git.uio.no:ifi-stolz-refaktor \\
3665 Commit & 43c16c04520746edd75f8dc2a1935781d3d9de6c \\
3666 \midrule
3667 \spancols{2}{Input data} \\
3668 \midrule
3669 Project & org.eclipse.jdt.ui \\
3670 Repository & git://git.eclipse.org/gitroot/jdt/eclipse.jdt.ui.git \\
3671 Commit & f218388fea6d4ec1da7ce22432726c244888bb6b \\
3672 Branch & R3\_8\_maintenance \\
3673 Tests suites & org.eclipse.jdt.ui.tests.AutomatedSuite,
3674 org.eclipse.jdt.ui.tests.refactoring.all.\-AllAllRefactoringTests \\
3675
3676 \bottomrule
3677 \end{tabularx}
3678\end{table}
98660ec0
EK
3679\subsection{Statistics}
3680The statistics gathered during the refactoring execution is presented in
3681\myref{tab:case1Statistics}.
3682
7fba220b
EK
3683\begin{table}[htb]
3684 \caption{Statistics after batch refactoring the Eclipse JDT UI project with
3685 the \ExtractAndMoveMethod refactoring.}
3686 \label{tab:case1Statistics}
3687 \centering
3688 \begin{tabularx}{\textwidth}{@{}>{\bfseries}L{1.5}R{0.5}@{}}
3689 \toprule
3690 \spancols{2}{Time used} \\
3691 \midrule
3692 Total time & 98m38s \\
3693 Analysis time & 14m41s (15\%) \\
3694 Change time & 74m20s (75\%) \\
3695 Miscellaneous tasks & 9m37s (10\%) \\
3696 \midrule
3697 \spancols{2}{Numbers of each type of entity analyzed} \\
3698 \midrule
3699 Packages & 110 \\
3700 Compilation units & 2,097 \\
3701 Types & 3,152 \\
3702 Methods & 27,667 \\
3703 Text selections & 591,500 \\
3704 \midrule
3705 \spancols{2}{Numbers for \ExtractAndMoveMethod refactoring candidates} \\
3706 \midrule
3707 Methods chosen as candidates & 2,552 \\
3708 Methods NOT chosen as candidates & 25,115 \\
3709 Candidate selections (multiple per method) & 36,843 \\
3710 \midrule
3711 \spancols{2}{\ExtractAndMoveMethod refactorings executed} \\
3712 \midrule
3713 Fully executed & 2,469 \\
3714 Not fully executed & 83 \\
3715 Total attempts & 2,552 \\
3716 \midrule
3717 \spancols{2}{Primitive refactorings executed} \\
3718 \spancols{2}{\small \ExtractMethod refactorings} \\
3719 \midrule
3720 Performed & 2,483 \\
3721 Not performed & 69 \\
3722 Total attempts & 2,552 \\
3723 \midrule
3724 \spancols{2}{\small \MoveMethod refactorings} \\
3725 \midrule
3726 Performed & 2469 \\
3727 Not performed & 14 \\
3728 Total attempts & 2,483 \\
3729
3730 \bottomrule
3731 \end{tabularx}
3732\end{table}
3733
98660ec0 3734\subsubsection{Execution time}
e36eade0 3735I consider the total execution time of approximately 1.5 hours as being
98660ec0
EK
3736acceptable. It clearly makes the batch process unsuitable for doing any
3737on-demand analysis or changes, but it is good enough for running periodic jobs,
3738like over-night analysis.
3739
3740As the statistics show, 75\% of the total time goes into making the actual code
3741changes. The time consumers are here the primitive \ExtractMethod and
3742\MoveMethod refactorings. Included in the change time is the parsing and
3743precondition checking done by the refactorings, as well as textual changes done
3744to files on disk. All this parsing and disk access is time-consuming, and
3745constitute a large part of the change time.
3746
3747In comparison, the pure analysis time, used to find suitable candidates, only
3748make up for 15\% of the total time consumed. This includes analyzing almost
3749600,000 text selections, while the number of attempted executions of the
3750\ExtractAndMoveMethod refactoring are only about 2,500. So the number of
3751executed primitive refactorings are approximately 5,000. Assuming the time used
3752on miscellaneous tasks are used mostly for parsing source code for the analysis,
3753we can say that the time used for analyzing code is at most 25\% of the total
3754time. This means that for every primitive refactoring executed, we can analyze
3755around 360 text selections. So, with an average of about 21 text selections per
3756method, it is reasonable to say that we can analyze over 15 methods in the time
3757it takes to perform a primitive refactoring.
3758
3759\subsubsection{Refactoring candidates}
3760Out of the 27,667 methods that was analyzed, 2,552 methods contained selections
3761that was considered candidates for the \ExtractAndMoveMethod refactoring. This
3762is roughly 9\% off the methods in the project. These 9\% of the methods had on
3763average 14.4 text selections that was considered considered possible refactoring
3764candidates.
3765
3766\subsubsection{Executed refactorings}
37672,469 out of 2,552 attempts on executing the \ExtractAndMoveMethod refactoring
3768was successful, giving a success rate of 96.7\%. The failure rate of 3.3\% stem
3769from situations where the analysis finds a candidate selection, but the change
3770execution fails. This failure could be an exception that was thrown, and the
3771refactoring aborts. It could also be the precondition checking for one of the
3772primitive refactorings that gives us an error status, meaning that if the
3773refactoring proceeds, the code will contain compilation errors afterwards,
3774forcing the composite refactoring to abort. This means that if the
3775\ExtractMethod refactoring fails, no attempt is done for the \MoveMethod
3776refactoring. \todo{Redundant information? Put in benchmark chapter?}
3777
3778Out of the 2,552 \ExtractMethod refactorings that was attempted executed, 69 of
3779them failed. This give a failure rate of 2.7\% for the primitive refactoring. In
3780comparison, the \MoveMethod refactoring had a failure rate of 0.6 \% of the
37812,483 attempts on the refactoring.
3782
3783\subsection{\name{SonarQube} analysis}
701c559a
EK
3784Results from the \name{SonarQube} analysis is shown in
3785\myref{tab:case1ResultsProfile1}.
98660ec0 3786
c9488804 3787\begin{table}[htb]
bc7b5d67
EK
3788 \caption{Results for analyzing the Eclipse JDT UI project, before and after
3789 the refactoring, with \name{SonarQube} and the \name{IFI Refaktor Case Study}
3790 quality profile. (Bold numbers are better.)}
c9488804
EK
3791 \label{tab:case1ResultsProfile1}
3792 \centering
c9488804
EK
3793 \begin{tabularx}{\textwidth}{@{}>{\bfseries}L{1.5}R{0.25}R{0.25}@{}}
3794 \toprule
bc7b5d67 3795 \textnormal{Number of issues for each rule} & Before & After \\
c9488804
EK
3796 \midrule
3797 Avoid too complex class & 81 & \textbf{79} \\
3798 Classes should not be coupled to too many other classes (Single
3799 Responsibility Principle) & \textbf{1,098} & 1,199 \\
3800 Control flow statements \ldots{} should not be nested too deeply & 1,375 &
3801 \textbf{1,285} \\
3802 Methods should not be too complex & 1,518 & \textbf{1,452} \\
3803 Methods should not have too many lines & 3,396 & \textbf{3,291} \\
3804 NPath Complexity & 348 & \textbf{329} \\
bc7b5d67 3805 Too many methods & \textbf{454} & 520 \\
6fabec9b 3806 \midrule
bc7b5d67 3807 Total number of issues & 8,270 & \textbf{8,155} \\
6fabec9b
EK
3808 \midrule
3809 \midrule
bc7b5d67 3810 \spancols{3}{Complexity} \\
6fabec9b
EK
3811 \midrule
3812 Per function & 3.6 & \textbf{3.3} \\
3813 Per class & \textbf{29.5} & 30.4 \\
3814 Per file & \textbf{44.0} & 45.3 \\
3815 \midrule
3816 Total complexity & \textbf{84,765} & 87,257 \\
3817 \midrule
3818 \midrule
bc7b5d67 3819 \spancols{3}{Numbers of each type of entity analyzed} \\
6fabec9b
EK
3820 \midrule
3821 Files & 1,926 & 1,926 \\
3822 Classes & 2,875 & 2,875 \\
3823 Functions & 23,744 & 26,332 \\
3824 Accessors & 1,296 & 1,019 \\
3825 Statements & 162,768 & 165,145 \\
3826 Lines of code & 320,941 & 329,112 \\
3827 \midrule
bc7b5d67 3828 Technical debt (in days) & \textbf{1,003.4} & 1,032.7 \\
c9488804
EK
3829 \bottomrule
3830 \end{tabularx}
3831\end{table}
6fabec9b 3832
701c559a 3833\subsubsection{Diversity in the number of entities analyzed}
e36eade0 3834The analysis performed by \name{SonarQube} is reporting fewer methods than found
701c559a
EK
3835by the pre-refactoring analysis. \name{SonarQube} discriminates between
3836functions (methods) and accessors, so the 1,296 accessors play a part in this
3837calculation. \name{SonarQube} also has the same definition as our plugin when
3838it comes to how a class is defined. Therefore is seems like \name{SonarQube}
3839misses 277 classes that our plugin handles. This can explain why the {SonarQube}
3840report differs from our numbers by approximately 2,500 methods,
3841
7fba220b
EK
3842\subsubsection{Complexity}
3843On all complexity rules that works on the method level, the number of issues
3844decreases with between 3.1\% and 6.5\% from before to after the refactoring. The
3845average complexity of a method decreases from 3.6 to 3.3, which is an
3846improvement of about 8.3\%. So, on the method level, the refactoring must be
3847said to have a slightly positive impact.
3848
3849The improvement in complexity on the method level is somewhat traded for
3850complexity on the class level. The complexity per class metric is worsen by 3\%
3851from before to after. The issues for the ``Too many methods'' rule also
3852increases by 14.5\%. These numbers indicate that the refactoring makes quite a
3853lot of the classes a little more complex overall. This is the expected outcome,
3854since the \ExtractAndMoveMethod refactoring introduces almost 2,500 new methods
3855into the project.
3856
3857The only number that can save the refactoring's impact on complexity on the
3858class level, is the ``Avoid too complex class'' rule. It improves with 2.5\%,
3859thus indicating that the complexity is moderately better distributed between the
3860classes after the refactoring than before.
3861
3862\subsubsection{Coupling}
3863One of the hopes when starting this project, was to be able to make a
3864refactoring that could lower the coupling between classes. Better complexity at
39884128 3865the method level is a not very unexpected byproduct of dividing methods into
7fba220b
EK
3866smaller parts. Lowering the coupling on the other hand, is a far greater task.
3867This is also reflected in the results for the only coupling rule defined in the
3868\name{SonarQube} quality profile, namely the ``Classes should not be coupled to
3869too many
3870other classes (Single Responsibility Principle)'' rule.
3871
3872The number of issues for the coupling rule is 1,098 before the refactoring, and
38731,199 afterwards. This is an increase in issues of 9.2\%, and a blow for this
3874project. These numbers can be interpreted two ways. The first possibility is
3875that our assumptions are wrong, and that increasing indirection does not
3876decrease coupling between classes. The other possibility is that our analysis
3877and choices of candidate text selections are not good enough. I vote for the
e36eade0 3878second possibility. (Voting against the public opinion may also be a little
7fba220b
EK
3879bold.)
3880
3881What probably happens is, that many of the times the \ExtractAndMoveMethod
3882refactoring is performed, the \MoveMethod refactoring ``drags'' with it
3883references to classes that are unknown to the method destination. If it happens
3884to be so lucky that it removes a dependency from one class, it might as well
3885introduce three new dependencies to another class. In those situations that a
3886class does not know about the originating class of a moved method, the
078b1e4a 3887\MoveMethod refactoring most certainly will introduce a dependency. This is
39884128 3888because there is a
078b1e4a 3889bug\footnote{\url{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=228635}} in the
39884128
EK
3890refactoring, making it pass an instance of the originating class as a reference
3891to the moved method, regardless of whether the reference is used in the method
3892body or not.
7fba220b
EK
3893
3894There is also the possibility that the heuristics used to find candidate text
3895selections are not good enough, they most certainly are not. I wish I had more
3896time to fine-tune them, and to complete the analysis part of the project, but
3897this is simply not the case. This becomes even clearer when analyzing the unit
3898test results for the after-code.
3899
3900\subsubsection{Totals}
3901On the bright side, the total number of issues is lower after the refactoring
3902than it was before. Before the refactoring, the total number of issues is
39038,270, and after it is 8,155. An improvement of only 1.4\%.
3904
3905Then \name{SonarQube} tells me that the total complexity has increased by
39062.9\%, and that the (more questionable) ``technical debt'' has increased from
39071,003.4 to 1,032.7 days, also a deterioration of 2.9\%. Although these numbers
3908are similar, no correlation has been found between them.
3909
3910\subsection{Unit tests}
39884128
EK
3911The tests that have been run for the \name{Eclipse JDT UI} project, are the
3912tests in the test suites specified as the main test suites on the JDT UI wiki
3913page on how to contribute to the
3914project\footnote{\url{https://wiki.eclipse.org/JDT\_UI/How\_to\_Contribute\#Unit\_Testing}}.
3915
3916\subsubsection{Before the refactoring}
3917Running the tests for the before-code of Eclipse JDT UI yielded 4 errors and 3
3918failures for the \type{AutomatedSuite} test suite (2,007 test cases), and 2
3919errors and
39203 failures for the \type{AllAllRefactoringTests} test suite (3,816 test cases).
3921
3922\subsubsection{After the refactoring}
3923The test results for the after-code of the Eclipse JDT UI project is another
01d46361
EK
3924story. The reason for this is that during the setup for the unit tests, Eclipse
3925now reports that the project contains 322 fatal errors, and a lot of errors that
3926probably follows from these. This is another blow for this master's project.
39884128
EK
3927
3928It has now been shown that the \ExtractAndMoveMethod refactoring, in its current
3929state, produces code that does not compile. Had these errors originated from
3930only one bug, it would not have been much of a problem, but this is not the
e36eade0 3931case. By only looking at some random compilation problems in the refactored code,
01d46361
EK
3932I came up with at least four different bugs \todo{write bug reports?} that
3933caused those problems. I then stopped looking for more, since some of the bugs
3934would take more time to fix than I could justify using on them at this point.
39884128
EK
3935
3936The only thing that can be said in my defence, is that all the compilation
3937errors could have been avoided if the type of situations that causes them was
3938properly handled by the primitive refactorings, that again are supported by the
e36eade0 3939Eclipse JDT UI project. All of the four randomly found bugs that I mentioned
39884128
EK
3940before, are also weaknesses of the \MoveMethod refactoring. If the primitive
3941refactorings had detected the up-coming errors
3942in their precondition checking phase, the refactorings would have been aborted,
3943since this is how the \ExtractAndMoveMethod refactoring handles such situations.
3944
3945Of course, taking all possible situations into account is an immense task. This
3946is one of the reasons for the failure. A complete analysis is too big of a task
3947for this master's project to handle. Looking at it now, this comes as no
3948surprise, since the task is obviously also too big for the creators of the
3949primitive \MoveMethod refactoring. This shows that the underlying primitive
3950refactorings are not complete enough to be fully relied upon for avoiding
3951compilation errors.
3952
3953Considering all these problems, it is difficult to know how to interpret the
3954unit test results from after refactoring the Eclipse JDT UI. The
3955\type{AutomatedSuite} reported 565 errors and 5 failures. Three of the failures
3956were the same as reported before the refactoring took place, so two of them are
3957new. For these two cases it is not immediately apparent what makes them behave
3958differently. The program is so complex that to analyze it to find this out, we
3959might need more powerful methods than just manually analyzing its source code.
3960This is somewhat characteristic for imperative programming: The programs are
3961often hard to analyze and understand.
3962
3963For the \type{AllAllRefactoringTests} test suite, the three failures are gone,
3964but the two errors have grown to 2,257 errors. I will not try to analyze those
3965errors.
3966
3967What I can say, is that it is likely that the \ExtractAndMoveMethod refactoring
3968has introduced some unintended behavioral changes. Let us say that the
3969refactoring introduces at least two behavior-altering changes for every 2,500
3970executions. More than that is difficult to say about the behavior-preserving
3971properties of the \ExtractAndMoveMethod refactoring, at this point.
3972
3973\subsection{Conclusions}
3974After automatically analyzing and executing the \ExtractAndMoveMethod
3975refactoring for all the methods in the Eclipse JDT UI project, the results does
3976not look that promising. For this case, the refactoring seems almost unusable as
3977it is now. The error rate and measurements done tells us this.
3978
3979The refactoring makes the code a little less complex at the method level. But
3980this is merely a side effect of extracting methods, and holds little scientific
3981value. When it comes to the overall complexity, it is increased, although it is
3982slightly better spread among the classes.
3983
3984The analysis done before the \ExtractAndMoveMethod refactoring, is currently not
3985complete enough to make the refactoring useful. It introduces too many errors in
3986the code, and the code may change it's behavior. It also remains to prove that
3987large scale refactoring with it can decrease coupling between classes. A better
3988analysis may prove this, but in its present state, the opposite is the fact. The
3989coupling measurements done by \name{SonarQube} shows this.
3990
3991On the bright side, the performance of the refactoring process is not that bad.
3992It shows that it is possible to make a tool the way we do, if we can make the
3993tool do anything useful. As long as the analysis phase is not going to involve
3994anything that uses to much disk access, a lot of analysis can be done in a
3995reasonable amount of time.
3996
3997The time used on performing the actual changes excludes a trial and error
3998approach with the tools used in this master's project. In a trial and error
3999approach, you could for instance be using the primitive refactorings used in
4000this project to refactor code, and only then make decisions based on the effect,
4001possibly shown by traditional software metrics. The problem with the approach
4002taken in this project, compared to a trial and error approach, is that using
4003heuristics beforehand is much more complicated. But on the other hand, a trial
4004and error approach would still need to face the challenges of producing code
4005that does compile without errors. If using refactorings that could produce
4006in-memory changes, a trial and error approach could be made more efficient.
078b1e4a
EK
4007
4008\section{Case 2: The \type{no.uio.ifi.refaktor} project}
01d46361 4009In this case we will see a form of the ``dogfooding'' methodology used, when
e36eade0 4010refactoring our own \type{no.uio.ifi.refaktor} project with the
078b1e4a
EK
4011\ExtractAndMoveMethod refactoring.
4012
4013In this case I will try to point out some differences from case 1, and how they
4014impact the execution of the benchmark. The refaktor project is 39 times smaller
4015than the Eclipse JDT UI project, measured in lines of code. This will make
4016things a bit more transparent. It will therefore be interesting to see if this
4017case can shed light on any aspect of our project that was lost in the larger
4018case 1.
4019
eb913f75
EK
4020The configuration for the experiment is specified in
4021\myref{tab:configurationCase2}.
4022
4023\begin{table}[htb]
4024 \caption{Configuration for Case 2.}
4025 \label{tab:configurationCase2}
4026 \centering
4027 \begin{tabularx}{\textwidth}{@{}>{\bfseries}L{0.67}L{1.33}@{}}
4028 \toprule
4029 \spancols{2}{Benchmark data} \\
4030 \midrule
4031 Launch configuration & CaseStudyDogfooding.launch \\
4032 Project & no.uio.ifi.refaktor.benchmark \\
4033 Repository & gitolite@git.uio.no:ifi-stolz-refaktor \\
4034 Commit & 43c16c04520746edd75f8dc2a1935781d3d9de6c \\
4035 \midrule
4036 \spancols{2}{Input data} \\
4037 \midrule
4038 Project & no.uio.ifi.refaktor \\
4039 Repository & gitolite@git.uio.no:ifi-stolz-refaktor \\
4040 Commit & 43c16c04520746edd75f8dc2a1935781d3d9de6c \\
4041 Branch & master \\
e36eade0 4042 Test configuration & no.uio.ifi.refaktor.tests/ExtractTest.launch \\
eb913f75
EK
4043 \bottomrule
4044 \end{tabularx}
4045\end{table}
078b1e4a 4046
eb913f75
EK
4047\subsection{Statistics}
4048The statistics gathered during the refactoring execution is presented in
4049\myref{tab:case2Statistics}.
4050
4051\begin{table}[htb]
4052 \caption{Statistics after batch refactoring the \type{no.uio.ifi.refaktor}
4053project with the \ExtractAndMoveMethod refactoring.}
4054 \label{tab:case2Statistics}
4055 \centering
4056 \begin{tabularx}{\textwidth}{@{}>{\bfseries}L{1.5}R{0.5}@{}}
4057 \toprule
4058 \spancols{2}{Time used} \\
4059 \midrule
4060 Total time & 1m15s \\
4061 Analysis time & 0m18s (24\%) \\
4062 Change time & 0m47s (63\%) \\
4063 Miscellaneous tasks & 0m10s (14\%) \\
4064 \midrule
4065 \spancols{2}{Numbers of each type of entity analyzed} \\
4066 \midrule
4067 Packages & 33 \\
4068 Compilation units & 154 \\
4069 Types & 168 \\
4070 Methods & 1,070 \\
4071 Text selections & 8,609 \\
4072 \midrule
4073 \spancols{2}{Numbers for \ExtractAndMoveMethod refactoring candidates} \\
4074 \midrule
4075 Methods chosen as candidates & 58 \\
4076 Methods NOT chosen as candidates & 1,012 \\
4077 Candidate selections (multiple per method) & 227 \\
4078 \midrule
4079 \spancols{2}{\ExtractAndMoveMethod refactorings executed} \\
4080 \midrule
4081 Fully executed & 53 \\
4082 Not fully executed & 5 \\
4083 Total attempts & 58 \\
4084 \midrule
4085 \spancols{2}{Primitive refactorings executed} \\
4086 \spancols{2}{\small \ExtractMethod refactorings} \\
4087 \midrule
4088 Performed & 56 \\
4089 Not performed & 2 \\
4090 Total attempts & 58 \\
4091 \midrule
4092 \spancols{2}{\small \MoveMethod refactorings} \\
4093 \midrule
4094 Performed & 53 \\
4095 Not performed & 3 \\
4096 Total attempts & 56 \\
4097
4098 \bottomrule
4099 \end{tabularx}
4100\end{table}
4101
078b1e4a
EK
4102\subsubsection{Differences}
4103There are some differences between the two projects that make them a little
4104difficult to compare by performance.
4105
4106\paragraph{Different complexity.}
4107Although the JDT UI project is 39 times greater than the refaktor project in
4108terms of lines of code, it is only about 26 times its size measured in numbers
4109of methods. This means that the methods in the refaktor project are smaller in
4110average than in the JDT project. This is also reflected in the \name{SonarQube}
4111report, where the complexity per method for the JDT project is 3.6, while the
4112refaktor project has a complexity per method of 2.1.
4113
4114\paragraph{Number of selections per method.}
4115The analysis for the JDT project processed 21 text selections per method in
4116average. This number for the refaktor project is only 8 selections per method
4117analyzed. This is a direct consequence of smaller methods.
4118
4119\paragraph{Different candidates to methods ratio.}
4120The differences in how the projects are factored are also reflected in the
4121ratios for how many methods that are chosen as candidates compared to the total
4122number of methods analyzed. For the JDT project, 9\% of the methods was
4123considered to be candidates, while for the refaktor project, only 5\% of the
4124methods was chosen.
4125
4126\paragraph{The average number of possible candidate selection.}
e36eade0 4127For the methods that are chosen as candidates, the average number of possible
078b1e4a
EK
4128candidate selections for these methods differ quite much. For the JDT project,
4129the number of possible candidate selections for these methods were 14.44
4130selections per method, while the candidate methods in the refaktor project had
4131only 3.91 candidate selections to choose from, in average.
4132
eb913f75 4133\subsubsection{Execution time}
078b1e4a 4134The differences in complexity, and the different candidate methods to total
e36eade0 4135number of methods ratios, is shown in the distributions of the execution times.
078b1e4a
EK
4136For the JDT project, 75\% of the total time was used on the actual changes,
4137while for the refaktor project, this number was only 63\%.
eb913f75 4138
078b1e4a
EK
4139For the JDT project, the benchmark used on average 0.21 seconds per method in
4140the project, while for the refaktor project it used only 0.07 seconds per
4141method. So the process used 3 times as much time per method for the JDT project
4142than for the refaktor project.
4143
4144While the JDT project is 39 times larger than the refaktor project measured in
4145lines of code, the benchmark used about 79 times as long time on it than for the
4146refaktor project. Relatively, this is about twice as long.
4147
4148Since the details of these execution times are not that relevant to this
4149master's project, only their magnitude, I will leave them here.
eb913f75
EK
4150
4151\subsubsection{Executed refactorings}
078b1e4a
EK
4152For the composite \ExtractAndMoveMethod refactoring performed in case 2, 53
4153successful attempts out of 58 gives a success rate of 91.4\%. This is 5.3
e36eade0 4154percentage points worse than for case 1.
eb913f75
EK
4155
4156\subsection{\name{SonarQube} analysis}
4157Results from the \name{SonarQube} analysis is shown in
4158\myref{tab:case2ResultsProfile1}.
4159
078b1e4a
EK
4160Not much is to be said about these results. The trends in complexity and
4161coupling are the same. We end up a little worse after the refactoring process
4162than before.
4163
eb913f75
EK
4164\begin{table}[htb]
4165 \caption{Results for analyzing the \var{no.uio.ifi.refaktor} project, before
4166 and after the refactoring, with \name{SonarQube} and the \name{IFI Refaktor
4167 Case Study} quality profile. (Bold numbers are better.)}
4168 \label{tab:case2ResultsProfile1}
4169 \centering
4170 \begin{tabularx}{\textwidth}{@{}>{\bfseries}L{1.5}R{0.25}R{0.25}@{}}
4171 \toprule
4172 \textnormal{Number of issues for each rule} & Before & After \\
4173 \midrule
4174 Avoid too complex class & 1 & 1 \\
4175 Classes should not be coupled to too many other classes (Single
4176 Responsibility Principle) & \textbf{29} & 34 \\
4177 Control flow statements \ldots{} should not be nested too deeply & 24 &
4178 \textbf{21} \\
4179 Methods should not be too complex & 17 & \textbf{15} \\
4180 Methods should not have too many lines & 41 & \textbf{40} \\
4181 NPath Complexity & 3 & 3 \\
4182 Too many methods & \textbf{13} & 15 \\
4183 \midrule
4184 Total number of issues & \textbf{128} & 129 \\
4185 \midrule
4186 \midrule
4187 \spancols{3}{Complexity} \\
4188 \midrule
4189 Per function & 2.1 & 2.1 \\
4190 Per class & \textbf{12.5} & 12.9 \\
4191 Per file & \textbf{13.8} & 14.2 \\
4192 \midrule
4193 Total complexity & \textbf{2,089} & 2,148 \\
4194 \midrule
4195 \midrule
4196 \spancols{3}{Numbers of each type of entity analyzed} \\
4197 \midrule
4198 Files & 151 & 151 \\
4199 Classes & 167 & 167 \\
4200 Functions & 987 & 1,045 \\
4201 Accessors & 35 & 30 \\
4202 Statements & 3,355 & 3,416 \\
078b1e4a 4203 Lines of code & 8,238 & 8,460 \\
eb913f75
EK
4204 \midrule
4205 Technical debt (in days) & \textbf{19.0} & 20.7 \\
4206 \bottomrule
4207 \end{tabularx}
4208\end{table}
4209
078b1e4a
EK
4210\subsection{Unit tests}
4211The tests used for this case are the same that has been developed throughout the
4212master's project.
4213
4214The code that was refactored for this case suffered from some of the problems
4215discovered in case 1. This means that the after-code for case 2 also contained
4216compilation errors, but they were not as many. The code contained only 6 errors
4217that made the code not compile.
4218
4219All of the errors made, originated from the same bug. It is a bug that happens
4220in situation where a class instance creation is moved from between packages, and
4221the class for the instance is package-private. The \MoveMethod refactoring does
e36eade0 4222not detect that there will be a visibility problem, and neither does it promote
078b1e4a
EK
4223the package-private class to be public.
4224
4225Since the errors was easy to fix manually, I corrected them and ran the unit
4226tests as planned. Before the refactoring, all tests passed. All tests also
4227passed after the refactoring, with the six error corrections. Since the
4228corrections done is not of a kind that could make the behavior of the program
4229change, it is likely that the refactorings done to the
4230\type{no.uio.ifi.refaktor} project did not change its behavior. This is also
4231supported by the informal experiment presented next.
4232
4233\subsection{An informal experiment}
e36eade0 4234To complete the task of ``eating my own dog food'', I conducted an informal
078b1e4a
EK
4235experiment where I used the refactored version of the \type{no.uio.ifi.refaktor}
4236project, with the corrections, to again refaktor ``itself''.
4237
4238The experiment produced code containing the same six errors as after the
4239previous experiment. I also compared the after-code from the two experiments
4240with a diff-tool. The only differences found was different method names. This is
4241expected, since the method names are randomly generated by the
4242\ExtractAndMoveMethod refactoring.
eb913f75 4243
078b1e4a
EK
4244The outcome of this simple experiment makes me more confident that the
4245\ExtractAndMoveMethod refactoring made only behavior-preserving changes to the
4246\type{no.uio.ifi.refaktor} project, apart from the compilation errors.
eb913f75 4247
078b1e4a
EK
4248\subsection{Conclusions}
4249The differences in complexity between the Eclipse JDT UI project and the
4250\type{no.uio.ifi.refaktor} project, clearly influenced the differences in their
4251execution times. This is mostly because fewer of the methods were chosen to be
4252refactored for the refaktor project than for the JDT project. What this makes
e36eade0 4253difficult, is to know if there are any severe performance penalties associated
078b1e4a 4254with refactoring on a large project compared to a small one.
eb913f75 4255
078b1e4a
EK
4256The trends in the \name{SonarQube} analysis are the same for this case as for
4257the previous one. This gives more confidence in the these results.
eb913f75 4258
078b1e4a
EK
4259By refactoring our own code and using it again to refactor our code, we showed
4260that it is possible to write an automated composite refactoring that works for
4261many cases. That it probably did not alter the behavior of a smaller project
4262shows us nothing more than that though, and might just be a coincidence.
eb913f75 4263
078b1e4a 4264\section{Summary}
01d46361 4265\todoin{Write? Or wrap up in final conclusions?}
c9488804 4266
bc7b5d67 4267\chapter{Benchmarking}\label{sec:benchmarking}
60065669 4268This part of the master's project is located in the \name{Eclipse} project
356782a0
EK
4269\code{no.uio.ifi.refaktor.benchmark}. The purpose of it is to run the equivalent
4270of the \type{SearchBasedExtractAndMoveMethodChanger}
4271\see{searchBasedExtractAndMoveMethodChanger} over a larger software project,
3ab3e132 4272both to test its robustness but also its effect on different software metrics.
356782a0
EK
4273
4274\section{The benchmark setup}
fe0a4c48 4275The benchmark itself is set up as a \name{JUnit} test case. This is a convenient
7940aed1
EK
4276setup, and utilizes the \name{JUnit Plugin Test Launcher}. This provides us with
4277a fully functional \name{Eclipse} workbench. Most importantly, this gives us
4278access to the Java Model of \name{Eclipse} \see{javaModel}.
356782a0
EK
4279
4280\subsection{The ProjectImporter}
4281The Java project that is going to be used as the data for the benchmark, must be
4282imported into the JUnit workspace. This is done by the
4283\typewithref{no.uio.ifi.refaktor.benchmark}{ProjectImporter}. The importer
4284require the absolute path to the project description file. It is named
4285\code{.project} and is located at the root of the project directory.
4286
4287The project description is loaded to find the name of the project to be
4288imported. The project that shall be the destination for the import is created in
4289the workspace, on the base of the name from the description. Then an import
4290operation is created, based on both the source and destination information. The
4291import operation is run to perform the import.
4292
4293I have found no simple API call to accomplish what the importer does, which
fe0a4c48
EK
4294tells me that it may not be too many people performing this particular action.
4295The solution to the problem was found on \name{Stack
356782a0 4296Overflow}\footnote{\url{https://stackoverflow.com/questions/12401297}}. It
3ab3e132 4297contains enough dirty details to be considered inconvenient to use, if not
356782a0
EK
4298wrapping it in a class like my \type{ProjectImporter}. One would probably have
4299to delve into the source code for the import wizard to find out how the import
4300operation works, if no one had already done it.
4301
8fe94c0b
EK
4302\section{Statistics}
4303Statistics for the analysis and changes is captured by the
4304\typewithref{no.uio.ifi.refaktor.aspects}{StatisticsAspect}. This an
fe0a4c48 4305\emph{aspect} written in \name{AspectJ}.
8fe94c0b
EK
4306
4307\subsection{AspectJ}
fe0a4c48 4308\name{AspectJ}\footnote{\url{http://eclipse.org/aspectj/}} is an extension to
8fe94c0b
EK
4309the Java language, and facilitates combining aspect-oriented programming with
4310the object-oriented programming in Java.
4311
4312Aspect-oriented programming is a programming paradigm that is meant to isolate
4313so-called \emph{cross-cutting concerns} into their own modules. These
dd73ba39
EK
4314cross-cutting concerns are functionalities that spans over multiple classes, but
4315may not belong naturally in any of them. It can be functionality that does not
4316concern the business logic of an application, and thus may be a burden when
4317entangled with parts of the source code it does not really belong. Examples
4318include logging, debugging, optimization and security.
8fe94c0b 4319
416b6888
EK
4320Aspects are interacting with other modules by defining advices. The concept of
4321an \emph{advice} is known from both aspect-oriented and functional
4322programming\citing{wikiAdvice2014}. It is a function that modifies another
4323function when the latter is run. An advice in AspectJ is somewhat similar to a
4324method in Java. It is meant to alter the behavior of other methods, and contains
4325a body that is executed when it is applied.
8fe94c0b
EK
4326
4327An advice can be applied at a defined \emph{pointcut}. A pointcut picks out one
4328or more \emph{join points}. A join point is a well-defined point in the
4329execution of a program. It can occur when calling a method defined for a
4330particular class, when calling all methods with the same name,
4331accessing/assigning to a particular field of a given class and so on. An advice
dd73ba39
EK
4332can be declared to run both before, after returning from a pointcut, when there
4333is thrown an exception in the pointcut or after the pointcut either returns or
4334throws an exception. In addition to picking out join points, a pointcut can
4335also bind variables from its context, so they can be accessed in the body of an
4336advice. An example of a pointcut and an advice is found in
4337\myref{lst:aspectjExample}.
8fe94c0b
EK
4338
4339\begin{listing}[h]
c8088eec 4340\begin{minted}{aspectj}
8fe94c0b
EK
4341pointcut methodAnalyze(
4342 SearchBasedExtractAndMoveMethodAnalyzer analyzer) :
4343 call(* SearchBasedExtractAndMoveMethodAnalyzer.analyze())
4344 && target(analyzer);
4345
4346after(SearchBasedExtractAndMoveMethodAnalyzer analyzer) :
4347 methodAnalyze(analyzer) {
4348 statistics.methodCount++;
4349 debugPrintMethodAnalysisProgress(analyzer.method);
4350}
4351\end{minted}
4352\caption{An example of a pointcut named \method{methodAnalyze},
4353and an advice defined to be applied after it has occurred.}
4354\label{lst:aspectjExample}
4355\end{listing}
4356
dd73ba39
EK
4357\subsection{The Statistics class}
4358The statistics aspect stores statistical information in an object of type
4359\type{Statistics}. As of now, the aspect needs to be initialized at the point in
4360time where it is desired that it starts its data gathering. At any point in time
4361the statistics aspect can be queried for a snapshot of the current statistics.
4362
4363The \type{Statistics} class also include functionality for generating a report
4364of its gathered statistics. The report can be given either as a string or it can
4365be written to a file.
4366
4367\subsection{Advices}
4368The statistics aspect contains advices for gathering statistical data from
4369different parts of the benchmarking process. It captures statistics from both
4370the analysis part and the execution part of the composite \ExtractAndMoveMethod
4371refactoring.
4372
4373For the analysis part, there are advices to count the number of text selections
4374analyzed and the number of methods, types, compilation units and packages
4375analyzed. There are also advices that counts for how many of the methods there
4376is found a selection that is a candidate for the refactoring, and for how many
3ab3e132 4377methods there is not.
dd73ba39
EK
4378
4379There exists advices for counting both the successful and unsuccessful
4380executions of all the refactorings. Both for the \ExtractMethod and \MoveMethod
4381refactorings in isolation, as well as for the combination of them.
4382
8fe94c0b 4383\section{Optimizations}
41293210 4384When looking for optimizations to make for the benchmarking process, I used the
60065669
EK
4385\name{VisualVM}\footnote{\url{http://visualvm.java.net/}} \gloss{profiler} for
4386the Java Virtual Machine to both profile the application and also to make memory
4387dumps of its heap.
8fe94c0b
EK
4388
4389\subsection{Caching}
60065669
EK
4390When \gloss{profiling} the benchmark process before making any optimizations, it
4391early became apparent that the parsing of source code was a place to direct
4392attention towards. This discovery was done when only \emph{analyzing} source
4393code, before trying to do any \emph{manipulation} of it. Caching of the parsed
4394ASTs seemed like the best way to save some time, as expected. With only a simple
4395cache of the most recently used AST, the analysis time was speeded up by a
4396factor of around 20. This number depends a little upon which type of system the
4397analysis is run.
41293210
EK
4398
4399The caching is managed by a cache manager, that now, by default, utilizes the
4400not so well known feature of Java called a \emph{soft reference}. Soft
4401references are best explained in the context of weak references. A \emph{weak
4402reference} is a reference to an object instance that is only guaranteed to
4403persist as long as there is a \emph{strong reference} or a soft reference
4404referring the same object. If no such reference is found, its referred object is
4405garbage collected. A strong reference is basically the same as a regular Java
4406reference. A soft reference has the same guarantees as a week reference when it
4407comes to its relation to strong references, but it is not necessarily garbage
4408collected whenever there exists no strong references to it. A soft reference
4409\emph{may} reside in memory as long as the JVM has enough free memory in the
4410heap. A soft reference will therefore usually perform better than a weak
4411reference when used for simple caching and similar tasks. The way to use a
4412soft/weak reference is to as it for its referent. The return value then has to
4413be tested to check that it is not \var{null}. For the basic usage of soft
4414references, see \myref{lst:softReferenceExample}. For a more thorough
4415explanation of weak references in general, see\citing{weakRef2006}.
4416
4417\begin{listing}[h]
4418\begin{minted}{java}
4419// Strong reference
4420Object strongRef = new Object();
4421
4422// Soft reference
4423SoftReference<Object> softRef =
4424 new SoftReference<Object>(new Object());
4425
4426// Using the soft reference
4427Object obj = softRef.get();
4428if (obj != null) {
4429 // Use object here
4430}
4431\end{minted}
4432\caption{Showing the basic usage of soft references. Weak references is used the
4433 same way. {\footnotesize (The references are part of the \code{java.lang.ref}
4434package.)}}
4435\label{lst:softReferenceExample}
4436\end{listing}
4437
4438The cache based on soft references has no limit for how many ASTs it caches. It
4439is generally not advisable to keep references to ASTs for prolonged periods of
4440time, since they are expensive structures to hold on to. For regular plugin
fe0a4c48 4441development, \name{Eclipse} recommends not creating more than one AST at a time to
41293210
EK
4442limit memory consumption. Since the benchmarking has nothing to do with user
4443experience, and throughput is everything, these advices are intentionally
fe0a4c48 4444ignored. This means that during the benchmarking process, the target \name{Eclipse}
41293210
EK
4445application may very well work close to its memory limit for the heap space for
4446long periods during the benchmark.
8fe94c0b 4447
81cf9554
EK
4448\subsection{Candidates stored as mementos}
4449When performing large scale analysis of source code for finding candidates to
4450the \ExtractAndMoveMethod refactoring, memory is an issue. One of the inputs to
4451the refactoring is a variable binding. This variable binding indirectly retains
4452a whole AST. Since ASTs are large structures, this quickly leads to an
4453\type{OutOfMemoryError} if trying to analyze a large project without optimizing
4454how we store the candidates data. This means that the JVM cannot allocate more
4455memory for out benchmark, and it exists disgracefully.
4456
4457A possible solution could be to just allow the JVM to allocate even more memory,
4458but this is not a dependable solution. The allocated memory could easily
4459supersede the physical memory of a machine, and that would make the benchmark go
4460really slow.
4461
4462Thus, the candidates data must be stored in another format. Therefore, we use
4463the \gloss{mementoPattern} to store the variable binding information. This is
4464done in a way that makes it possible to retrieve the variable binding at a later
4465point. The data that is stored to achieve this, is the key to the original
4466variable binding. In addition to the key, we know which method and text
4467selection the variable is referenced in, so that we can find it by parsing the
4468source code and search for it when it is needed.
356782a0 4469
98660ec0
EK
4470\section{Handling failures}
4471\todoin{write}
4472
a7514fbd
EK
4473
4474\chapter{Technicalities}
4475
4476\section{Source code organization}
60065669 4477All the parts of this master's project is under version control with
a7514fbd
EK
4478\name{Git}\footnote{\url{http://git-scm.com/}}.
4479
4480The software written is organized as some \name{Eclipse} plugins. Writing a plugin is
4481the natural way to utilize the API of \name{Eclipse}. This also makes it possible to
4482provide a user interface to manually run operations on selections in program
4483source code or whole projects/packages.
4484
4485When writing a plugin in \name{Eclipse}, one has access to resources such as the
4486current workspace, the open editor and the current selection.
4487
4488The thesis work is contained in the following Eclipse projects:
4489
4490\begin{description}
4491 \item[no.uio.ifi.refaktor] \hfill \\ This is the main Eclipse plugin
4492 project, and contains all of the business logic for the plugin.
4493
4494 \item[no.uio.ifi.refaktor.tests] \hfill \\
4495 This project contains the tests for the main plugin.
4496
4497 \item[no.uio.ifi.refaktor.examples] \hfill \\
4498 Contains example code used in testing. It also contains code for managing
4499 this example code, such as creating an Eclipse project from it before a test
4500 run.
4501
4502 \item[no.uio.ifi.refaktor.benchmark] \hfill \\
4503 This project contains code for running search based versions of the
4504 composite refactoring over selected Eclipse projects.
4505
4506 \item[no.uio.ifi.refaktor.releng] \hfill \\
4507 Contains the rmap, queries and target definitions needed by by Buckminster
4508 on the Jenkins continuous integration server.
4509
4510\end{description}
4511
4512\subsection{The no.uio.ifi.refaktor project}
4513
4514\subsubsection{no.uio.ifi.refaktor.analyze}
e36eade0
EK
4515This package, and its sub-packages, contains code that is used for analyzing
4516Java source code. The most important sub-packages are presented below.
a7514fbd
EK
4517
4518\begin{description}
4519 \item[no.uio.ifi.refaktor.analyze.analyzers] \hfill \\
4520 This package contains source code analyzers. These are usually responsible
4521 for analyzing text selections or running specialized analyzers for different
4522 kinds of entities. Their structure are often hierarchical. This means that
4523 you have an analyzer for text selections, that in turn is utilized by an
4524 analyzer that analyzes all the selections of a method. Then there are
4525 analyzers for analyzing all the methods of a type, all the types of a
4526 compilation unit, all the compilation units of a package, and, at last, all
4527 of the packages in a project.
4528
4529 \item[no.uio.ifi.refaktor.analyze.checkers] \hfill \\
4530 A package containing checkers. The checkers are classes used to validate
4531 that a selection can be further analyzed and chosen as a candidate for a
4532 refactoring. Invalidating properties can be such as usage of inner classes
4533 or the need for multiple return values.
4534
4535 \item[no.uio.ifi.refaktor.analyze.collectors] \hfill \\
4536 This package contains the property collectors. Collectors are used to gather
4537 properties from a text selection. This is mostly properties regarding
4538 referenced names and their occurrences. It is these properties that makes up
4539 the basis for finding the best candidates for a refactoring.
4540\end{description}
4541
4542\subsubsection{no.uio.ifi.refaktor.change}
e36eade0 4543This package, and its sub-packages, contains functionality for manipulate source
a7514fbd
EK
4544code.
4545
4546\begin{description}
4547 \item[no.uio.ifi.refaktor.change.changers] \hfill \\
4548 This package contains source code changers. They are used to glue together
4549 the analysis of source code and the actual execution of the changes.
4550
4551 \item[no.uio.ifi.refaktor.change.executors] \hfill \\
4552 The executors that are responsible for making concrete changes are found in
4553 this package. They are mostly used to create and execute one or more Eclipse
4554 refactorings.
4555
4556 \item[no.uio.ifi.refaktor.change.processors] \hfill \\
4557 Contains a refactoring processor for the \MoveMethod refactoring. The code
4558 is stolen and modified to fix a bug. The related bug is described in
4559 \myref{eclipse_bug_429416}.
4560
4561\end{description}
4562
4563\subsubsection{no.uio.ifi.refaktor.handlers}
4564This package contains handlers for the commands defined in the plugin manifest.
4565
4566\subsubsection{no.uio.ifi.refaktor.prefix}
4567This package contains the \type{Prefix} type that is the data representation of
4568the prefixes found by the \type{PrefixesCollector}. It also contains the prefix
4569set for storing and working with prefixes.
4570
4571\subsubsection{no.uio.ifi.refaktor.statistics}
4572The package contains statistics functionality. Its heart is the statistics
4573aspect that is responsible for gathering statistics during the execution of the
4574\ExtractAndMoveMethod refactoring.
4575
4576\begin{description}
4577 \item[no.uio.ifi.refaktor.statistics.reports] \hfill \\
4578 This package contains a simple framework for generating reports from the
4579 statistics data generated by the aspect. Currently, the only available
4580 report type is a simple text report.
4581
4582\end{description}
4583
4584
4585\subsubsection{no.uio.ifi.refaktor.textselection}
4586This package contains the two custom text selections that are used extensively
4587throughout the project. One of them is just a subclass of the other, to support
4588the use of the memento pattern to optimize the memory usage during benchmarking.
4589
4590\subsubsection{no.uio.ifi.refaktor.debugging}
4591The package contains a debug utility class. I addition to this, the package
4592\code{no.uio.ifi.refaktor.utils.aspects} contains a couple of aspects used for
4593debugging purposes.
4594
4595\subsubsection{no.uio.ifi.refaktor.utils}
4596Utility package that contains all the functionality that has to do with parsing
4597of source code. It also has utility classes for looking up handles to methods
4598and types et cetera.
4599
4600\begin{description}
4601 \item[no.uio.ifi.refaktor.utils.caching] \hfill \\
4602 This package contains the caching manager for compilation units, along with
4603 classes for different caching strategies.
4604
4605 \item[no.uio.ifi.refaktor.utils.nullobjects] \hfill \\
4606 Contains classes for creating different null objects. Most of the classes is
4607 used to represent null objects of different handle types. These null objects
4608 are returned from various utility classes instead of returning a \var{null}
4609 value when other values are not available.
4610
4611\end{description}
4612
4613\section{Continuous integration}
4614The continuous integration server
4615\name{Jenkins}\footnote{\url{http://jenkins-ci.org/}} has been set up for the
4616project\footnote{A work mostly done by the supervisor.}. It is used as a way to
4617run tests and perform code coverage analysis.
4618
4619To be able to build the \name{Eclipse} plugins and run tests for them with Jenkins, the
4620component assembly project
4621\name{Buckminster}\footnote{\url{http://www.eclipse.org/buckminster/}} is used,
4622through its plugin for Jenkins. Buckminster provides for a way to specify the
4623resources needed for building a project and where and how to find them.
4624Buckminster also handles the setup of a target environment to run the tests in.
4625All this is needed because the code to build depends on an \name{Eclipse}
4626installation with various plugins.
4627
4628\subsection{Problems with AspectJ}
4629The Buckminster build worked fine until introducing AspectJ into the project.
4630When building projects using AspectJ, there are some additional steps that needs
4631to be performed. First of all, the aspects themselves must be compiled. Then the
4632aspects needs to be woven with the classes they affect. This demands a process
4633that does multiple passes over the source code.
4634
4635When using AspectJ with \name{Eclipse}, the specialized compilation and the
4636weaving can be handled by the \name{AspectJ Development
4637Tools}\footnote{\url{https://www.eclipse.org/ajdt/}}. This works all fine, but
4638it complicates things when trying to build a project depending on \name{Eclipse}
4639plugins outside of \name{Eclipse}. There is supposed to be a way to specify a
4640compiler adapter for javac, together with the file extensions for the file types
4641it shall operate. The AspectJ compiler adapter is called
4642\typewithref{org.aspectj.tools.ant.taskdefs}{Ajc11CompilerAdapter}, and it works
4643with files that has the extensions \code{*.java} and \code{*.aj}. I tried to
4644setup this in the build properties file for the project containing the aspects,
4645but to no avail. The project containing the aspects does not seem to be built at
4646all, and the projects that depends on it complains that they cannot find certain
4647classes.
4648
4649I then managed to write an \name{Ant}\footnote{\url{https://ant.apache.org/}}
4650build file that utilizes the AspectJ compiler adapter, for the
4651\code{no.uio.ifi.refaktor} plugin. The problem was then that it could no longer
4652take advantage of the environment set up by Buckminster. The solution to this
4653particular problem was of a ``hacky'' nature. It involves exporting the plugin
4654dependencies for the project to an Ant build file, and copy the exported path
4655into the existing build script. But then the Ant script needs to know where the
4656local \name{Eclipse} installation is located. This is no problem when building
4657on a local machine, but to utilize the setup done by Buckminster is a problem
4658still unsolved. To get the classpath for the build setup correctly, and here
4659comes the most ``hacky'' part of the solution, the Ant script has a target for
4660copying the classpath elements into a directory relative to the project
4661directory and checking it into Git. When no \code{ECLIPSE\_HOME} property is set
4662while running Ant, the script uses the copied plugins instead of the ones
4663provided by the \name{Eclipse} installation when building the project. This
4664obviously creates some problems with maintaining the list of dependencies in the
4665Ant file, as well as remembering to copy the plugins every time the list of
4666dependencies change.
4667
4668The Ant script described above is run by Jenkins before the Buckminster setup
4669and build. When setup like this, the Buckminster build succeeds for the projects
4670not using AspectJ, and the tests are run as normal. This is all good, but it
4671feels a little scary, since the reason for Buckminster not working with AspectJ
4672is still unknown.
4673
4674The problems with building with AspectJ on the Jenkins server lasted for a
4675while, before they were solved. This is reflected in the ``Test Result Trend''
4676and ``Code Coverage Trend'' reported by Jenkins.
4677
4678
4928aa0b 4679
0cbeeadb
EK
4680\chapter{Conclusions and Future Work}
4681\todoin{Write}
4682
4683\section{Future work}
4684
0cbeeadb
EK
4685
4686\appendix
4687
4688
3727b75b 4689\chapter{Eclipse Bugs Found}
540ca7e4
EK
4690\newcommand{\submittedBugReport}[1]{The submitted bug report can be found on
4691 \url{#1}.}
94bb49f0
EK
4692
4693\section{Eclipse bug 420726: Code is broken when moving a method that is
0f6e45f8
EK
4694assigning to the parameter that is also the move
4695destination}\label{eclipse_bug_420726}
540ca7e4 4696This bug
94bb49f0 4697was found when analyzing what kinds of names that was to be considered as
3727b75b 4698\emph{unfixes} \see{unfixes}.
94bb49f0
EK
4699
4700\subsection{The bug}
4701The bug emerges when trying to move a method from one class to another, and when
4702the target for the move (must be a variable, local or field) is both a parameter
fe0a4c48 4703variable and also is assigned to within the method body. \name{Eclipse} allows this to
94bb49f0
EK
4704happen, although it is the sure path to a compilation error. This is because we
4705would then have an assignment to a \var{this} expression, which is not allowed
540ca7e4
EK
4706in Java.
4707\submittedBugReport{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=420726}
94bb49f0
EK
4708
4709\subsection{The solution}
4710The solution to this problem is to add all simple names that are assigned to in
4711a method body to the set of unfixes.
128adb4f 4712
f1b6174d
EK
4713\section{Eclipse bug 429416: IAE when moving method from anonymous
4714class}\label{eclipse_bug_429416}
540ca7e4 4715I discovered
128adb4f
EK
4716this bug during a batch change on the \type{org.eclipse.jdt.ui} project.
4717
4718\subsection{The bug}
fe0a4c48 4719This bug surfaces when trying to use the \refa{Move Method} refactoring to move a
94bb49f0 4720method from an anonymous class to another class. This happens both for my
fe0a4c48
EK
4721simulation as well as in \name{Eclipse}, through the user interface. It only occurs
4722when \name{Eclipse} analyzes the program and finds it necessary to pass an instance of
94bb49f0 4723the originating class as a parameter to the moved method. I.e. it want to pass a
128adb4f
EK
4724\var{this} expression. The execution ends in an
4725\typewithref{java.lang}{IllegalArgumentException} in
4726\typewithref{org.eclipse.jdt.core.dom}{SimpleName} and its
4727\method{setIdentifier(String)} method. The simple name is attempted created in
4728the method
4729\methodwithref{org.eclipse.jdt.internal.corext.refactoring.structure.\\MoveInstanceMethodProcessor}{createInlinedMethodInvocation}
4730so the \type{MoveInstanceMethodProcessor} was early a clear suspect.
4731
4732The \method{createInlinedMethodInvocation} is the method that creates a method
4733invocation where the previous invocation to the method that was moved was. From
4734its code it can be read that when a \var{this} expression is going to be passed
4735in to the invocation, it shall be qualified with the name of the original
3ab3e132 4736method's declaring class, if the declaring class is either an anonymous class or
128adb4f
EK
4737a member class. The problem with this, is that an anonymous class does not have
4738a name, hence the term \emph{anonymous} class! Therefore, when its name, an
4739empty string, is passed into
4740\methodwithref{org.eclipse.jdt.core.dom.AST}{newSimpleName} it all ends in an
540ca7e4
EK
4741\type{IllegalArgumentException}.
4742\submittedBugReport{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=429416}
128adb4f
EK
4743
4744\subsection{How I solved the problem}
4745Since the \type{MoveInstanceMethodProcessor} is instantiated in the
4746\typewithref{no.uio.ifi.refaktor.change.executors}{MoveMethod\-RefactoringExecutor},
4747and only need to be a
4748\typewithref{org.eclipse.ltk.core.refactoring.participants}{MoveProcessor}, I
4749was able to copy the code for the original move processor and modify it so that
4750it works better for me. It is now called
f1b6174d 4751\typewithref{no.uio.ifi.refaktor.change.processors}{ModifiedMoveInstanceMethodProcessor}.
128adb4f
EK
4752The only modification done (in addition to some imports and suppression of
4753warnings), is in the \method{createInlinedMethodInvocation}. When the declaring
4754class of the method to move is anonymous, the \var{this} expression in the
4755parameter list is not qualified with the declaring class' (empty) name.
4756
3727b75b
EK
4757\section{Eclipse bug 429954: Extracting statement with reference to local type
4758breaks code}\label{eclipse_bug_429954}
540ca7e4 4759The bug
a6415293 4760was discovered when doing some changes to the way unfixes is computed.
3727b75b
EK
4761
4762\subsection{The bug}
fe0a4c48 4763The problem is that \name{Eclipse} is allowing selections that references variables of
3727b75b
EK
4764local types to be extracted. When this happens the code is broken, since the
4765extracted method must take a parameter of a local type that is not in the
4766methods scope. The problem is illustrated in
540ca7e4
EK
4767\myref{lst:extractMethod_LocalClass}, but there in another setting.
4768\submittedBugReport{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=429954}
3727b75b
EK
4769
4770\subsection{Actions taken}
4771There are no actions directly springing out of this bug, since the Extract
a6415293 4772Method refactoring cannot be meant to be this way. This is handled on the
fe0a4c48 4773analysis stage of our \refa{Extract and Move Method} refactoring. So names representing
3727b75b
EK
4774variables of local types is considered unfixes \see{unfixes}.
4775\todoin{write more when fixing this in legal statements checker}
9ff90080 4776\backmatter{}
fe0a4c48 4777\printglossaries
9ff90080 4778\printbibliography
055dca93 4779\listoftodos
9ff90080 4780\end{document}