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