]> git.uio.no Git - ifi-stolz-refaktor.git/blame - thesis/master-thesis-erlenkr.tex
Thesis: test-driven development methodology
[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}
4e468834 9\usepackage{tabularx}
d11bcf4d
EK
10\usepackage{tikz}
11\usepackage{tikz-qtree}
5e5908eb 12\usetikzlibrary{shapes,snakes,trees,arrows,shadows,positioning,calc}
ae138b9d
EK
13\usepackage{babel,textcomp,csquotes,ifimasterforside}
14
15\usepackage{varioref}
79d5c2a9 16\usepackage[hidelinks]{hyperref}
8b6b22c8 17\usepackage{cleveref}
b4a197fd 18\usepackage[xindy]{glossaries}
ae138b9d 19
fe0a4c48 20\usepackage[style=alphabetic,backend=biber]{biblatex}
12c254af 21\usepackage{amsthm}
3471cd15 22\usepackage{mathtools}
0ab2e134
EK
23\usepackage{graphicx}
24% use 'disable' before printing:
25\usepackage[]{todonotes}
0d7fbd88
EK
26\usepackage{xspace}
27\usepackage{he-she}
b289552b 28\usepackage{verbatim}
ddcea0b5 29\usepackage{minted}
347ed677 30\usepackage{multicol}
ddcea0b5 31\usemintedstyle{bw}
8fae7b44
EK
32\usepackage{perpage} %the perpage package
33\MakePerPage{footnote} %the perpage package command
9ff90080 34
6c51af15 35\theoremstyle{definition}
12c254af 36\newtheorem*{wordDef}{Definition}
3471cd15 37\newtheorem*{theorem}{Theorem}
12c254af 38
ddcea0b5
EK
39\graphicspath{ {./figures/} }
40
8b6b22c8 41\newcommand{\citing}[1]{~\cite{#1}}
e123ab03
EK
42%\newcommand{\myref}[1]{\cref{#1} on \cpageref{#1}}
43\newcommand{\myref}[1]{\vref{#1}}
4306ef44 44\newcommand{\Myref}[1]{\Vref{#1}}
8b6b22c8 45
b4a197fd 46%\newcommand{\glossref}[1]{\textsuperscript{(\glsrefentry{#1})}}
20bcc7bf
EK
47%\newcommand{\gloss}[1]{\gls{#1}\glossref{#1}}
48%\newcommand{\glosspl}[1]{\glspl{#1}\glossref{#1}}
49\newcommand{\gloss}[1]{\gls{#1}}
50\newcommand{\glosspl}[1]{\glspl{#1}}
fe0a4c48 51
12c254af 52\newcommand{\definition}[1]{\begin{wordDef}#1\end{wordDef}}
8b6b22c8 53\newcommand{\see}[1]{(see \myref{#1})}
137e0e7b
EK
54\newcommand{\explanation}[3]{\noindent\textbf{\textit{#1}}\\*\emph{When:}
55#2\\*\emph{How:} #3\\*[-7px]}
4e135659 56
128adb4f 57%\newcommand{\type}[1]{\lstinline{#1}}
03674629
EK
58\newcommand{\code}[1]{\texttt{\textbf{#1}}}
59\newcommand{\type}[1]{\code{#1}}
f041551b
EK
60\newcommand{\typeref}[1]{\footnote{\type{#1}}}
61\newcommand{\typewithref}[2]{\type{#2}\typeref{#1.#2}}
62\newcommand{\method}[1]{\type{#1}}
63\newcommand{\methodref}[2]{\footnote{\type{#1}\method{\##2()}}}
64\newcommand{\methodwithref}[2]{\method{#2}\footnote{\type{#1}\method{\##2()}}}
3510e539 65\newcommand{\var}[1]{\type{#1}}
9ff90080 66
fe0a4c48
EK
67\newcommand{\name}[1]{#1}
68\newcommand{\tit}[1]{\emph{#1}}
69\newcommand{\refa}[1]{\emph{#1}}
70\newcommand{\pattern}[1]{\emph{#1}}
71\newcommand{\metr}[1]{\emph{#1}}
72\newcommand{\ExtractMethod}{\refa{Extract Method}\xspace}
73\newcommand{\MoveMethod}{\refa{Move Method}\xspace}
74\newcommand{\ExtractAndMoveMethod}{\refa{Extract and Move Method}\xspace}
b5c7bb1b 75
7125ceac 76\newcommand\todoin[2][]{\todo[inline, caption={#2}, #1]{
4e135659
EK
77\begin{minipage}{\textwidth-4pt}#2\end{minipage}}}
78
cbc3b044
EK
79\title{Automated Composition of Refactorings}
80\subtitle{Composing the Extract and Move Method refactorings in Eclipse}
7c28933b
EK
81\author{Erlend Kristiansen}
82
fe0a4c48
EK
83\makeglossaries
84\newglossaryentry{profiling}
85{
86 name=profiling,
87 description={is to run a computer program through a profiler/with a profiler
88 attached}
89}
20bcc7bf
EK
90\newglossaryentry{profiler}
91{
92 name=profiler,
93 description={A profiler is a program for analyzing performance within an
94 application. It is used to analyze memory consumption, processing time and
95frequency of procedure calls and such.}
96}
97\newglossaryentry{xUnit}
98{
99 name={xUnit framework},
100 description={An xUnit framework is a framework for writing unit tests for a
101 computer program. It follows the patterns known from the JUnit framework for
102 Java\citing{fowlerXunit}
103 },
104 plural={xUnit frameworks}
105}
fe0a4c48
EK
106\newglossaryentry{softwareObfuscation}
107{
108 name={software obfuscation},
109 description={makes source code harder to read and analyze, while preserving
110 its semantics}
111}
112\newglossaryentry{extractClass}
113{
114 name=\refa{Extract Class},
115 description={The \refa{Extract Class} refactoring works by creating a class,
116for then to move members from another class to that class and access them from
117the old class via a reference to the new class}
118}
119\newglossaryentry{designPattern}
120{
121 name={design pattern},
122 description={A design pattern is a named abstraction, that is meant to solve a
123 general design problem. It describes the key aspects of a common problem and
124identifies its participators and how they collaborate},
125 plural={design patterns}
126}
b4a197fd
EK
127%\newglossaryentry{extractMethod}
128%{
129% name=\refa{Extract Method},
130% description={The \refa{Extract Method} refactoring is used to extract a
131%fragment of code from its context and into a new method. A call to the new
132%method is inlined where the fragment was before. It is used to break code into
133%logical units, with names that explain their purpose}
134%}
135%\newglossaryentry{moveMethod}
136%{
137% name=\refa{Move Method},
138% description={The \refa{Move Method} refactoring is used to move a method from
139% one class to another. This is useful if the method is using more features of
140% another class than of the class which it is currently defined. Then all calls
141% to this method must be updated, or the method must be copied, with the old
142%method delegating to the new method}
143%}
f5fb40e4 144
7c28933b 145\bibliography{bibliography/master-thesis-erlenkr-bibliography}
9ff90080 146
c8088eec
EK
147% UML comment in TikZ:
148% ref: https://tex.stackexchange.com/questions/103688/folded-paper-shape-tikz
43ca7be4
EK
149\makeatletter
150\pgfdeclareshape{umlcomment}{
151 \inheritsavedanchors[from=rectangle] % this is nearly a rectangle
152 \inheritanchorborder[from=rectangle]
153 \inheritanchor[from=rectangle]{center}
154 \inheritanchor[from=rectangle]{north}
155 \inheritanchor[from=rectangle]{south}
156 \inheritanchor[from=rectangle]{west}
157 \inheritanchor[from=rectangle]{east}
158 % ... and possibly more
159 \backgroundpath{% this is new
160 % store lower right in xa/ya and upper right in xb/yb
161 \southwest \pgf@xa=\pgf@x \pgf@ya=\pgf@y
162 \northeast \pgf@xb=\pgf@x \pgf@yb=\pgf@y
163 % compute corner of ‘‘flipped page’’
164 \pgf@xc=\pgf@xb \advance\pgf@xc by-10pt % this should be a parameter
165 \pgf@yc=\pgf@yb \advance\pgf@yc by-10pt
166 % construct main path
167 \pgfpathmoveto{\pgfpoint{\pgf@xa}{\pgf@ya}}
168 \pgfpathlineto{\pgfpoint{\pgf@xa}{\pgf@yb}}
169 \pgfpathlineto{\pgfpoint{\pgf@xc}{\pgf@yb}}
170 \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@yc}}
171 \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@ya}}
172 \pgfpathclose
173 % add little corner
174 \pgfpathmoveto{\pgfpoint{\pgf@xc}{\pgf@yb}}
175 \pgfpathlineto{\pgfpoint{\pgf@xc}{\pgf@yc}}
176 \pgfpathlineto{\pgfpoint{\pgf@xb}{\pgf@yc}}
177 \pgfpathlineto{\pgfpoint{\pgf@xc}{\pgf@yc}}
178 }
179}
180\makeatother
181
182\tikzstyle{comment}=[%
183 draw,
184 drop shadow,
185 fill=white,
186 align=center,
187 shape=document,
188 minimum width=20mm,
189 minimum height=10mm,
190 shape=umlcomment,
191 inner sep=2ex,
192 font=\ttfamily,
193]
194
f5fb40e4
EK
195%\interfootnotelinepenalty=10000
196
9ff90080 197\begin{document}
fe0a4c48 198\pagenumbering{roman}
531c4132 199\ififorside
9ff90080 200\frontmatter{}
9ff90080
EK
201
202
203\chapter*{Abstract}
064227e3
EK
204\todoin{\textbf{Remove all todos (including list) before delivery/printing!!!
205Can be done by removing ``draft'' from documentclass.}}
889ba93e 206\todoin{Write abstract}
9ff90080
EK
207
208\tableofcontents{}
209\listoffigures{}
210\listoftables{}
211
212\chapter*{Preface}
213
d1adbeef
EK
214The discussions in this report must be seen in the context of object oriented
215programming languages, and Java in particular, since that is the language in
216which most of the examples will be given. All though the techniques discussed
217may be applicable to languages from other paradigms, they will not be the
218subject of this report.
f3a108c3 219
055dca93 220\mainmatter
00aa0588 221
740e1b6c 222\chapter{What is Refactoring?}
7c28933b 223
f3a108c3
EK
224This question is best answered by first defining the concept of a
225\emph{refactoring}, what it is to \emph{refactor}, and then discuss what aspects
a1bafe90 226of programming make people want to refactor their code.
00aa0588 227
740e1b6c 228\section{Defining refactoring}
a1bafe90 229Martin Fowler, in his classic book on refactoring\citing{refactoring}, defines a
00aa0588 230refactoring like this:
ee45c41f 231
00aa0588 232\begin{quote}
aa1e3779
EK
233 \emph{Refactoring} (noun): a change made to the internal
234 structure\footnote{The structure observable by the programmer.} of software to
235 make it easier to understand and cheaper to modify without changing its
236 observable behavior.~\cite[p.~53]{refactoring}
00aa0588 237\end{quote}
ee45c41f 238
a1bafe90 239\noindent This definition assigns additional meaning to the word
ee45c41f
EK
240\emph{refactoring}, beyond the composition of the prefix \emph{re-}, usually
241meaning something like ``again'' or ``anew'', and the word \emph{factoring},
6c51af15
EK
242that can mean to isolate the \emph{factors} of something. Here a \emph{factor}
243would be close to the mathematical definition of something that divides a
244quantity, without leaving a remainder. Fowler is mixing the \emph{motivation}
a1bafe90
EK
245behind refactoring into his definition. Instead it could be more refined, formed
246to only consider the \emph{mechanical} and \emph{behavioral} aspects of
247refactoring. That is to factor the program again, putting it together in a
248different way than before, while preserving the behavior of the program. An
249alternative definition could then be:
6c51af15
EK
250
251\definition{A \emph{refactoring} is a transformation
8fae7b44 252done to a program without altering its external behavior.}
00aa0588 253
ee1d883a
EK
254From this we can conclude that a refactoring primarily changes how the
255\emph{code} of a program is perceived by the \emph{programmer}, and not the
740e1b6c
EK
256\emph{behavior} experienced by any user of the program. Although the logical
257meaning is preserved, such changes could potentially alter the program's
258behavior when it comes to performance gain or -penalties. So any logic depending
259on the performance of a program could make the program behave differently after
260a refactoring.
00aa0588 261
fe0a4c48
EK
262In the extreme case one could argue that \gloss{softwareObfuscation} is
263refactoring. It is often used to protect proprietary software. It restrains
264uninvited viewers, so they have a hard time analyzing code that they are not
265supposed to know how works. This could be a problem when using a language that
266is possible to decompile, such as Java.
b4e539f7
EK
267
268Obfuscation could be done composing many, more or less randomly chosen,
269refactorings. Then the question arises whether it can be called a
270\emph{composite refactoring} or not \see{compositeRefactorings}? The answer is
271not obvious. First, there is no way to describe the mechanics of software
272obfuscation, because there are infinitely many ways to do that. Second,
273obfuscation can be thought of as \emph{one operation}: Either the code is
274obfuscated, or it is not. Third, it makes no sense to call software obfuscation
275\emph{a refactoring}, since it holds different meaning to different people.
276
277This last point is important, since one of the motivations behind defining
278different refactorings, is to establish a \emph{vocabulary} for software
279professionals to use when reasoning about and discussing programs, similar to
fe0a4c48 280the motivation behind \glosspl{designPattern}\citing{designPatterns}.
b4e539f7
EK
281\begin{comment}
282So for describing \emph{software obfuscation}, it might be more appropriate to
283define what you do when performing it rather than precisely defining its
284mechanics in terms of other refactorings.
285\end{comment}
00aa0588 286
740e1b6c 287\section{The etymology of 'refactoring'}
f3a108c3
EK
288It is a little difficult to pinpoint the exact origin of the word
289``refactoring'', as it seems to have evolved as part of a colloquial
290terminology, more than a scientific term. There is no authoritative source for a
291formal definition of it.
292
b5c7bb1b 293According to Martin Fowler\citing{etymology-refactoring}, there may also be more
f3a108c3 294than one origin of the word. The most well-known source, when it comes to the
b4e539f7
EK
295origin of \emph{refactoring}, is the
296Smalltalk\footnote{\label{footNote}Programming language} community and their
fe0a4c48 297infamous \name{Refactoring
f3a108c3 298Browser}\footnote{\url{http://st-www.cs.illinois.edu/users/brant/Refactory/RefactoringBrowser.html}}
fe0a4c48 299described in the article \tit{A Refactoring Tool for
b5c7bb1b
EK
300Smalltalk}\citing{refactoringBrowser1997}, published in 1997.
301Allegedly\citing{etymology-refactoring}, the metaphor of factoring programs was
b4e539f7 302also present in the Forth\textsuperscript{\ref{footNote}} community, and the
fe0a4c48
EK
303word ``refactoring'' is mentioned in a book by Leo Brodie, called \tit{Thinking
304Forth}\citing{brodie2004}, first published in 1984\footnote{\tit{Thinking Forth}
305was first published in 1984 by the \name{Forth Interest Group}. Then it was
306reprinted in 1994 with minor typographical corrections, before it was
b4e539f7
EK
307transcribed into an electronic edition typeset in \LaTeX\ and published under a
308Creative Commons licence in
3092004. The edition cited here is the 2004 edition, but the content should
310essentially be as in 1984.}. The exact word is only printed one
311place~\cite[p.~232]{brodie2004}, but the term \emph{factoring} is prominent in
312the book, that also contains a whole chapter dedicated to (re)factoring, and how
313to keep the (Forth) code clean and maintainable.
ee45c41f 314
f3a108c3
EK
315\begin{quote}
316 \ldots good factoring technique is perhaps the most important skill for a
3a154bb7 317 Forth programmer.~\cite[p.~172]{brodie2004}
f3a108c3 318\end{quote}
ee45c41f
EK
319
320\noindent Brodie also express what \emph{factoring} means to him:
321
f3a108c3
EK
322\begin{quote}
323 Factoring means organizing code into useful fragments. To make a fragment
324 useful, you often must separate reusable parts from non-reusable parts. The
325 reusable parts become new definitions. The non-reusable parts become arguments
3a154bb7 326 or parameters to the definitions.~\cite[p.~172]{brodie2004}
f3a108c3
EK
327\end{quote}
328
329Fowler claims that the usage of the word \emph{refactoring} did not pass between
fe0a4c48 330the \name{Forth} and \name{Smalltalk} communities, but that it emerged
f3a108c3
EK
331independently in each of the communities.
332
740e1b6c 333\section{Motivation -- Why people refactor}
2f6e6dec
EK
334There are many reasons why people want to refactor their programs. They can for
335instance do it to remove duplication, break up long methods or to introduce
b4e539f7
EK
336design patterns into their software systems. The shared trait for all these are
337that peoples' intentions are to make their programs \emph{better}, in some
338sense. But what aspects of their programs are becoming improved?
339
340As just mentioned, people often refactor to get rid of duplication. They are
341moving identical or similar code into methods, and are pushing methods up or
342down in their class hierarchies. They are making template methods for
343overlapping algorithms/functionality, and so on. It is all about gathering what
344belongs together and putting it all in one place. The resulting code is then
345easier to maintain. When removing the implicit coupling\footnote{When
346 duplicating code, the duplicate pieces of code might not be coupled, apart
347from representing the same functionality. So if this functionality is going to
348change, it might need to change in more than one place, thus creating an
349implicit coupling between multiple pieces of code.} between code snippets, the
137e0e7b 350location of a bug is limited to only one place, and new functionality need only
a1bafe90
EK
351to be added to this one place, instead of a number of places people might not
352even remember.
353
354A problem you often encounter when programming, is that a program contains a lot
355of long and hard-to-grasp methods. It can then help to break the methods into
b4a197fd
EK
356smaller ones, using the \ExtractMethod refactoring\citing{refactoring}. Then
357you may discover something about a program that you were not aware of before;
358revealing bugs you did not know about or could not find due to the complex
359structure of your program. \todo{Proof?} Making the methods smaller and giving
360good names to the new ones clarifies the algorithms and enhances the
a1bafe90
EK
361\emph{understandability} of the program \see{magic_number_seven}. This makes
362refactoring an excellent method for exploring unknown program code, or code that
363you had forgotten that you wrote.
364
b4e539f7
EK
365Most primitive refactorings are simple, and usually involves moving code
366around\citing{kerievsky2005}. The motivation behind them may first be revealed
367when they are combined into larger --- higher level --- refactorings, called
a1bafe90 368\emph{composite refactorings} \see{compositeRefactorings}. Often the goal of
b4e539f7
EK
369such a series of refactorings is a design pattern. Thus the design can
370\emph{evolve} throughout the lifetime of a program, as opposed to designing
371up-front. It is all about being structured and taking small steps to improve a
372program's design.
a1bafe90
EK
373
374Many software design pattern are aimed at lowering the coupling between
375different classes and different layers of logic. One of the most famous is
fe0a4c48
EK
376perhaps the \pattern{Model-View-Controller}\citing{designPatterns} pattern. It
377is aimed at lowering the coupling between the user interface, the business logic
b4e539f7
EK
378and the data representation of a program. This also has the added benefit that
379the business logic could much easier be the target of automated tests, thus
380increasing the productivity in the software development process.
0b0567f2
EK
381
382Another effect of refactoring is that with the increased separation of concerns
a1bafe90
EK
383coming out of many refactorings, the \emph{performance} can be improved. When
384profiling programs, the problematic parts are narrowed down to smaller parts of
385the code, which are easier to tune, and optimization can be performed only where
b4e539f7 386needed and in a more effective way\citing{refactoring}.
137e0e7b 387
b01d328a
EK
388Last, but not least, and this should probably be the best reason to refactor, is
389to refactor to \emph{facilitate a program change}. If one has managed to keep
390one's code clean and tidy, and the code is not bloated with design patterns that
a1bafe90 391are not ever going to be needed, then some refactoring might be needed to
b01d328a
EK
392introduce a design pattern that is appropriate for the change that is going to
393happen.
394
137e0e7b
EK
395Refactoring program code --- with a goal in mind --- can give the code itself
396more value. That is in the form of robustness to bugs, understandability and
a1bafe90
EK
397maintainability. Having robust code is an obvious advantage, but
398understandability and maintainability are both very important aspects of
399software development. By incorporating refactoring in the development process,
400bugs are found faster, new functionality is added more easily and code is easier
401to understand by the next person exposed to it, which might as well be the
402person who wrote it. The consequence of this, is that refactoring can increase
403the average productivity of the development process, and thus also add to the
404monetary value of a business in the long run. The perspective on productivity
405and money should also be able to open the eyes of the many nearsighted managers
406that seldom see beyond the next milestone.
137e0e7b 407
b01d328a 408\section{The magical number seven}\label{magic_number_seven}
fe0a4c48
EK
409The article \tit{The magical number seven, plus or minus two: some limits on our
410capacity for processing information}\citing{miller1956} by George A. Miller,
411was published in the journal \name{Psychological Review} in 1956. It presents
412evidence that support that the capacity of the number of objects a human being
413can hold in its working memory is roughly seven, plus or minus two objects. This
414number varies a bit depending on the nature and complexity of the objects, but
415is according to Miller ``\ldots never changing so much as to be
f4cea2d6
EK
416unrecognizable.''
417
418Miller's article culminates in the section called \emph{Recoding}, a term he
419borrows from communication theory. The central result in this section is that by
420recoding information, the capacity of the amount of information that a human can
421process at a time is increased. By \emph{recoding}, Miller means to group
b4e539f7
EK
422objects together in chunks, and give each chunk a new name that it can be
423remembered by.
f4cea2d6
EK
424
425\begin{quote}
426 \ldots recoding is an extremely powerful weapon for increasing the amount of
4cb06723 427 information that we can deal with.~\cite[p.~95]{miller1956}
f4cea2d6 428\end{quote}
ee45c41f 429
b4e539f7
EK
430By organizing objects into patterns of ever growing depth, one can memorize and
431process a much larger amount of data than if it were to be represented as its
432basic pieces. This grouping and renaming is analogous to how many refactorings
433work, by grouping pieces of code and give them a new name. Examples are the
fe0a4c48 434fundamental \ExtractMethod and \refa{Extract Class}
b4e539f7
EK
435refactorings\citing{refactoring}.
436
a1bafe90 437An example from the article addresses the problem of memorizing a sequence of
b4e539f7
EK
438binary digits. The example presented here is a slightly modified version of the
439one presented in the original article\citing{miller1956}, but it preserves the
3ab3e132 440essence of it. Let us say we have the following sequence of
f4cea2d6
EK
44116 binary digits: ``1010001001110011''. Most of us will have a hard time
442memorizing this sequence by only reading it once or twice. Imagine if we instead
443translate it to this sequence: ``A273''. If you have a background from computer
b4e539f7
EK
444science, it will be obvious that the latter sequence is the first sequence
445recoded to be represented by digits in base 16. Most people should be able to
f4cea2d6
EK
446memorize this last sequence by only looking at it once.
447
448Another result from the Miller article is that when the amount of information a
449human must interpret increases, it is crucial that the translation from one code
450to another must be almost automatic for the subject to be able to remember the
0d7fbd88 451translation, before \heshe is presented with new information to recode. Thus
f4cea2d6
EK
452learning and understanding how to best organize certain kinds of data is
453essential to efficiently handle that kind of data in the future. This is much
a1bafe90
EK
454like when humans learn to read. First they must learn how to recognize letters.
455Then they can learn distinct words, and later read sequences of words that form
456whole sentences. Eventually, most of them will be able to read whole books and
457briefly retell the important parts of its content. This suggest that the use of
b4e539f7
EK
458design patterns is a good idea when reasoning about computer programs. With
459extensive use of design patterns when creating complex program structures, one
460does not always have to read whole classes of code to comprehend how they
461function, it may be sufficient to only see the name of a class to almost fully
462understand its responsibilities.
f4cea2d6
EK
463
464\begin{quote}
465 Our language is tremendously useful for repackaging material into a few chunks
4cb06723 466 rich in information.~\cite[p.~95]{miller1956}
f4cea2d6 467\end{quote}
ee45c41f 468
a1bafe90 469Without further evidence, these results at least indicate that refactoring
f4cea2d6
EK
470source code into smaller units with higher cohesion and, when needed,
471introducing appropriate design patterns, should aid in the cause of creating
b4e539f7 472computer programs that are easier to maintain and have code that is easier (and
f4cea2d6
EK
473better) understood.
474
740e1b6c 475\section{Notable contributions to the refactoring literature}
bd94b131 476\todoin{Thinking Forth?}
36d99783 477
d21ef41f
EK
478\begin{description}
479 \item[1992] William F. Opdyke submits his doctoral dissertation called
fe0a4c48
EK
480 \tit{Refactoring Object-Oriented Frameworks}\citing{opdyke1992}. This work
481 defines a set of refactorings, that are behavior preserving given that their
482 preconditions are met. The dissertation is focused on the automation of
483 refactorings.
484 \item[1999] Martin Fowler et al.: \tit{Refactoring: Improving the Design of
b5c7bb1b
EK
485 Existing Code}\citing{refactoring}. This is maybe the most influential text
486 on refactoring. It bares similarities with Opdykes thesis\citing{opdyke1992}
d21ef41f
EK
487 in the way that it provides a catalog of refactorings. But Fowler's book is
488 more about the craft of refactoring, as he focuses on establishing a
489 vocabulary for refactoring, together with the mechanics of different
490 refactorings and when to perform them. His methodology is also founded on
fe0a4c48
EK
491 the principles of test-driven development.
492 \item[2005] Joshua Kerievsky: \tit{Refactoring to
36d99783 493 Patterns}\citing{kerievsky2005}. This book is heavily influenced by Fowler's
fe0a4c48 494 \tit{Refactoring}\citing{refactoring} and the ``Gang of Four'' \tit{Design
36d99783
EK
495 Patterns}\citing{designPatterns}. It is building on the refactoring
496 catalogue from Fowler's book, but is trying to bridge the gap between
497 \emph{refactoring} and \emph{design patterns} by providing a series of
498 higher-level composite refactorings, that makes code evolve toward or away
fe0a4c48 499 from certain design patterns. The book is trying to build up the reader's
36d99783
EK
500 intuition around \emph{why} one would want to use a particular design
501 pattern, and not just \emph{how}. The book is encouraging evolutionary
e123ab03 502 design \see{relationToDesignPatterns}.
d21ef41f 503\end{description}
3b7c1d90 504
110dae91 505\section{Tool support (for Java)}\label{toolSupport}
3ab3e132 506This section will briefly compare the refactoring support of the three IDEs
fe0a4c48
EK
507\name{Eclipse}\footnote{\url{http://www.eclipse.org/}}, \name{IntelliJ
508IDEA}\footnote{The IDE under comparison is the \name{Community Edition},
4e135659 509\url{http://www.jetbrains.com/idea/}} and
fe0a4c48 510\name{NetBeans}\footnote{\url{https://netbeans.org/}}. These are the most
4e135659
EK
511popular Java IDEs\citing{javaReport2011}.
512
513All three IDEs provide support for the most useful refactorings, like the
514different extract, move and rename refactorings. In fact, Java-targeted IDEs are
515known for their good refactoring support, so this did not appear as a big
516surprise.
517
518The IDEs seem to have excellent support for the \ExtractMethod refactoring, so
b4e539f7
EK
519at least they have all passed the first ``refactoring
520rubicon''\citing{fowlerRubicon2001,secondRubicon2012}.
4e135659 521
b4a197fd
EK
522Regarding the \MoveMethod refactoring, the \name{Eclipse} and \name{IntelliJ}
523IDEs do the job in very similar manners. In most situations they both do a
524satisfying job by producing the expected outcome. But they do nothing to check
525that the result does not break the semantics of the program \see{correctness}.
fe0a4c48 526The \name{NetBeans} IDE implements this refactoring in a somewhat
b4e539f7
EK
527unsophisticated way. For starters, the refactoring's default destination for the
528move, is the same class as the method already resides in, although it refuses to
529perform the refactoring if chosen. But the worst part is, that if moving the
530method \method{f} of the class \type{C} to the class \type{X}, it will break the
531code. The result is shown in \myref{lst:moveMethod_NetBeans}.
4e135659 532
347ed677
EK
533\begin{listing}
534\begin{multicols}{2}
4e135659
EK
535\begin{minted}[samepage]{java}
536public class C {
537 private X x;
538 ...
539 public void f() {
540 x.m();
541 x.n();
542 }
543}
544\end{minted}
545
347ed677 546\columnbreak
4e135659
EK
547
548\begin{minted}[samepage]{java}
549public class X {
550 ...
551 public void f(C c) {
552 c.x.m();
553 c.x.n();
554 }
555}
556\end{minted}
347ed677
EK
557\end{multicols}
558\caption{Moving method \method{f} from \type{C} to \type{X}.}
559\label{lst:moveMethod_NetBeans}
560\end{listing}
4e135659 561
fe0a4c48 562\name{NetBeans} will try to create code that call the methods \method{m} and \method{n}
4e135659 563of \type{X} by accessing them through \var{c.x}, where \var{c} is a parameter of
a1bafe90
EK
564type \type{C} that is added the method \method{f} when it is moved. (This is
565seldom the desired outcome of this refactoring, but ironically, this ``feature''
fe0a4c48 566keeps \name{NetBeans} from breaking the code in the example from \myref{correctness}.)
8b6b22c8 567If \var{c.x} for some reason is inaccessible to \type{X}, as in this case, the
fe0a4c48 568refactoring breaks the code, and it will not compile. \name{NetBeans} presents a
8b6b22c8
EK
569preview of the refactoring outcome, but the preview does not catch it if the IDE
570is about break the program.
4778044b 571
b4e539f7 572The IDEs under investigation seem to have fairly good support for primitive
fe0a4c48
EK
573refactorings, but what about more complex ones, such as
574\gloss{extractClass}\citing{refactoring}? \name{IntelliJ} handles this in a
575fairly good manner, although, in the case of private methods, it leaves unused
a1bafe90 576methods behind. These are methods that delegate to a field with the type of the
fe0a4c48
EK
577new class, but are not used anywhere. \name{Eclipse} has added its own quirk to
578the \refa{Extract Class} refactoring, and only allows for \emph{fields} to be
579moved to a new class, \emph{not methods}. This makes it effectively only
580extracting a data structure, and calling it \refa{Extract Class} is a little
b4e539f7 581misleading. One would often be better off with textual extract and paste than
fe0a4c48
EK
582using the \refa{Extract Class} refactoring in \name{Eclipse}. When it comes to
583\name{NetBeans}, it does not even show an attempt on providing this refactoring.
4778044b 584
36d99783 585\section{The relation to design patterns}\label{relationToDesignPatterns}
4cb06723 586
fe0a4c48
EK
587Refactoring and design patterns have at least one thing in common, they are both
588promoted by advocates of \emph{clean code}\citing{cleanCode} as fundamental
589tools on the road to more maintainable and extendable source code.
4cb06723
EK
590
591\begin{quote}
592 Design patterns help you determine how to reorganize a design, and they can
593 reduce the amount of refactoring you need to do
594 later.~\cite[p.~353]{designPatterns}
595\end{quote}
596
a1bafe90
EK
597Although sometimes associated with
598over-engineering\citing{kerievsky2005,refactoring}, design patterns are in
599general assumed to be good for maintainability of source code. That may be
d1adbeef
EK
600because many of them are designed to support the \emph{open/closed principle} of
601object-oriented programming. The principle was first formulated by Bertrand
602Meyer, the creator of the Eiffel programming language, like this: ``Modules
603should be both open and closed.''\citing{meyer1988} It has been popularized,
604with this as a common version:
605
606\begin{quote}
607 Software entities (classes, modules, functions, etc.) should be open for
608 extension, but closed for modification.\footnote{See
609 \url{http://c2.com/cgi/wiki?OpenClosedPrinciple} or
610 \url{https://en.wikipedia.org/wiki/Open/closed_principle}}
611\end{quote}
612
613Maintainability is often thought of as the ability to be able to introduce new
a1bafe90 614functionality without having to change too much of the old code. When
d1adbeef
EK
615refactoring, the motivation is often to facilitate adding new functionality. It
616is about factoring the old code in a way that makes the new functionality being
617able to benefit from the functionality already residing in a software system,
618without having to copy old code into new. Then, next time someone shall add new
a1bafe90
EK
619functionality, it is less likely that the old code has to change. Assuming that
620a design pattern is the best way to get rid of duplication and assist in
621implementing new functionality, it is reasonable to conclude that a design
622pattern often is the target of a series of refactorings. Having a repertoire of
623design patterns can also help in knowing when and how to refactor a program to
624make it reflect certain desired characteristics.
d1adbeef
EK
625
626\begin{quote}
a1bafe90 627 There is a natural relation between patterns and refactorings. Patterns are
d1adbeef
EK
628 where you want to be; refactorings are ways to get there from somewhere
629 else.~\cite[p.~107]{refactoring}
630\end{quote}
631
632This quote is wise in many contexts, but it is not always appropriate to say
a1bafe90
EK
633``Patterns are where you want to be\ldots''. \emph{Sometimes}, patterns are
634where you want to be, but only because it will benefit your design. It is not
635true that one should always try to incorporate as many design patterns as
636possible into a program. It is not like they have intrinsic value. They only add
637value to a system when they support its design. Otherwise, the use of design
638patterns may only lead to a program that is more complex than necessary.
d1adbeef
EK
639
640\begin{quote}
641 The overuse of patterns tends to result from being patterns happy. We are
642 \emph{patterns happy} when we become so enamored of patterns that we simply
643 must use them in our code.~\cite[p.~24]{kerievsky2005}
644\end{quote}
645
646This can easily happen when relying largely on up-front design. Then it is
647natural, in the very beginning, to try to build in all the flexibility that one
648believes will be necessary throughout the lifetime of a software system.
649According to Joshua Kerievsky ``That sounds reasonable --- if you happen to be
650psychic.''~\cite[p.~1]{kerievsky2005} He is advocating what he believes is a
651better approach: To let software continually evolve. To start with a simple
652design that meets today's needs, and tackle future needs by refactoring to
653satisfy them. He believes that this is a more economic approach than investing
654time and money into a design that inevitably is going to change. By relying on
655continuously refactoring a system, its design can be made simpler without
656sacrificing flexibility. To be able to fully rely on this approach, it is of
e123ab03 657utter importance to have a reliable suit of tests to lean on \see{testing}. This
d1adbeef
EK
658makes the design process more natural and less characterized by difficult
659decisions that has to be made before proceeding in the process, and that is
660going to define a project for all of its unforeseeable future.
661
b289552b
EK
662\begin{comment}
663
137e0e7b
EK
664\section{Classification of refactorings}
665% only interesting refactorings
666% with 2 detailed examples? One for structured and one for intra-method?
667% Is replacing Bubblesort with Quick Sort considered a refactoring?
668
669\subsection{Structural refactorings}
670
f65da046 671\subsubsection{Primitive refactorings}
137e0e7b
EK
672
673% Composing Methods
674\explanation{Extract Method}{You have a code fragment that can be grouped
675together.}{Turn the fragment into a method whose name explains the purpose of
676the method.}
677
678\explanation{Inline Method}{A method's body is just as clear as its name.}{Put
679the method's body into the body of its callers and remove the method.}
680
681\explanation{Inline Temp}{You have a temp that is assigned to once with a simple
682expression, and the temp is getting in the way of other refactorings.}{Replace
683all references to that temp with the expression}
684
685% Moving Features Between Objects
686\explanation{Move Method}{A method is, or will be, using or used by more
687features of another class than the class on which it is defined.}{Create a new
688method with a similar body in the class it uses most. Either turn the old method
689into a simple delegation, or remove it altogether.}
690
691\explanation{Move Field}{A field is, or will be, used by another class more than
692the class on which it is defined}{Create a new field in the target class, and
693change all its users.}
694
695% Organizing Data
696\explanation{Replace Magic Number with Symbolic Constant}{You have a literal
697number with a particular meaning.}{Create a constant, name it after the meaning,
698and replace the number with it.}
699
700\explanation{Encapsulate Field}{There is a public field.}{Make it private and
701provide accessors.}
702
703\explanation{Replace Type Code with Class}{A class has a numeric type code that
8fae7b44 704does not affect its behavior.}{Replace the number with a new class.}
137e0e7b
EK
705
706\explanation{Replace Type Code with Subclasses}{You have an immutable type code
8fae7b44 707that affects the behavior of a class.}{Replace the type code with subclasses.}
137e0e7b
EK
708
709\explanation{Replace Type Code with State/Strategy}{You have a type code that
8fae7b44 710affects the behavior of a class, but you cannot use subclassing.}{Replace the
137e0e7b
EK
711type code with a state object.}
712
713% Simplifying Conditional Expressions
714\explanation{Consolidate Duplicate Conditional Fragments}{The same fragment of
8fae7b44 715code is in all branches of a conditional expression.}{Move it outside of the
137e0e7b
EK
716expression.}
717
718\explanation{Remove Control Flag}{You have a variable that is acting as a
719control flag fro a series of boolean expressions.}{Use a break or return
720instead.}
721
722\explanation{Replace Nested Conditional with Guard Clauses}{A method has
8fae7b44 723conditional behavior that does not make clear the normal path of
137e0e7b
EK
724execution.}{Use guard clauses for all special cases.}
725
8fae7b44 726\explanation{Introduce Null Object}{You have repeated checks for a null
137e0e7b
EK
727value.}{Replace the null value with a null object.}
728
729\explanation{Introduce Assertion}{A section of code assumes something about the
730state of the program.}{Make the assumption explicit with an assertion.}
731
732% Making Method Calls Simpler
733\explanation{Rename Method}{The name of a method does not reveal its
734purpose.}{Change the name of the method}
735
736\explanation{Add Parameter}{A method needs more information from its
737caller.}{Add a parameter for an object that can pass on this information.}
738
739\explanation{Remove Parameter}{A parameter is no longer used by the method
740body.}{Remove it.}
741
742%\explanation{Parameterize Method}{Several methods do similar things but with
743%different values contained in the method.}{Create one method that uses a
744%parameter for the different values.}
745
746\explanation{Preserve Whole Object}{You are getting several values from an
747object and passing these values as parameters in a method call.}{Send the whole
748object instead.}
749
750\explanation{Remove Setting Method}{A field should be set at creation time and
751never altered.}{Remove any setting method for that field.}
752
753\explanation{Hide Method}{A method is not used by any other class.}{Make the
754method private.}
755
8fae7b44
EK
756\explanation{Replace Constructor with Factory Method}{You want to do more than
757simple construction when you create an object}{Replace the constructor with a
137e0e7b
EK
758factory method.}
759
760% Dealing with Generalization
8fae7b44 761\explanation{Pull Up Field}{Two subclasses have the same field.}{Move the field
137e0e7b
EK
762to the superclass.}
763
764\explanation{Pull Up Method}{You have methods with identical results on
765subclasses.}{Move them to the superclass.}
766
8fae7b44 767\explanation{Push Down Method}{Behavior on a superclass is relevant only for
137e0e7b
EK
768some of its subclasses.}{Move it to those subclasses.}
769
770\explanation{Push Down Field}{A field is used only by some subclasses.}{Move the
771field to those subclasses}
772
773\explanation{Extract Interface}{Several clients use the same subset of a class's
8fae7b44 774interface, or two classes have part of their interfaces in common.}{Extract the
137e0e7b
EK
775subset into an interface.}
776
777\explanation{Replace Inheritance with Delegation}{A subclass uses only part of a
778superclasses interface or does not want to inherit data.}{Create a field for the
779superclass, adjust methods to delegate to the superclass, and remove the
780subclassing.}
781
782\explanation{Replace Delegation with Inheritance}{You're using delegation and
783are often writing many simple delegations for the entire interface}{Make the
784delegating class a subclass of the delegate.}
785
786\subsubsection{Composite refactorings}
787
788% Composing Methods
789% \explanation{Replace Method with Method Object}{}{}
790
791% Moving Features Between Objects
792\explanation{Extract Class}{You have one class doing work that should be done by
793two}{Create a new class and move the relevant fields and methods from the old
794class into the new class.}
795
796\explanation{Inline Class}{A class isn't doing very much.}{Move all its features
797into another class and delete it.}
798
799\explanation{Hide Delegate}{A client is calling a delegate class of an
800object.}{Create Methods on the server to hide the delegate.}
801
802\explanation{Remove Middle Man}{A class is doing to much simple delegation.}{Get
803the client to call the delegate directly.}
804
805% Organizing Data
806\explanation{Replace Data Value with Object}{You have a data item that needs
8fae7b44 807additional data or behavior.}{Turn the data item into an object.}
137e0e7b
EK
808
809\explanation{Change Value to Reference}{You have a class with many equal
810instances that you want to replace with a single object.}{Turn the object into a
811reference object.}
812
813\explanation{Encapsulate Collection}{A method returns a collection}{Make it
8fae7b44 814return a read-only view and provide add/remove methods.}
137e0e7b
EK
815
816% \explanation{Replace Array with Object}{}{}
817
818\explanation{Replace Subclass with Fields}{You have subclasses that vary only in
819methods that return constant data.}{Change the methods to superclass fields and
820eliminate the subclasses.}
821
822% Simplifying Conditional Expressions
823\explanation{Decompose Conditional}{You have a complicated conditional
824(if-then-else) statement.}{Extract methods from the condition, then part, an
825else part.}
826
827\explanation{Consolidate Conditional Expression}{You have a sequence of
828conditional tests with the same result.}{Combine them into a single conditional
829expression and extract it.}
830
831\explanation{Replace Conditional with Polymorphism}{You have a conditional that
8fae7b44 832chooses different behavior depending on the type of an object.}{Move each leg
137e0e7b
EK
833of the conditional to an overriding method in a subclass. Make the original
834method abstract.}
835
836% Making Method Calls Simpler
837\explanation{Replace Parameter with Method}{An object invokes a method, then
838passes the result as a parameter for a method. The receiver can also invoke this
839method.}{Remove the parameter and let the receiver invoke the method.}
840
841\explanation{Introduce Parameter Object}{You have a group of parameters that
842naturally go together.}{Replace them with an object.}
843
844% Dealing with Generalization
845\explanation{Extract Subclass}{A class has features that are used only in some
846instances.}{Create a subclass for that subset of features.}
847
848\explanation{Extract Superclass}{You have two classes with similar
849features.}{Create a superclass and move the common features to the
850superclass.}
851
852\explanation{Collapse Hierarchy}{A superclass and subclass are not very
853different.}{Merge them together.}
854
855\explanation{Form Template Method}{You have two methods in subclasses that
856perform similar steps in the same order, yet the steps are different.}{Get the
857steps into methods with the same signature, so that the original methods become
858the same. Then you can pull them up.}
859
860
861\subsection{Functional refactorings}
862
863\explanation{Substitute Algorithm}{You want to replace an algorithm with one
864that is clearer.}{Replace the body of the method with the new algorithm.}
00aa0588 865
b289552b 866\end{comment}
00aa0588
EK
867
868\section{The impact on software quality}
869
a1bafe90 870\subsection{What is software quality?}
00aa0588 871The term \emph{software quality} has many meanings. It all depends on the
9a55a5bc 872context we put it in. If we look at it with the eyes of a software developer, it
a1bafe90 873usually means that the software is easily maintainable and testable, or in other
9a55a5bc
EK
874words, that it is \emph{well designed}. This often correlates with the
875management scale, where \emph{keeping the schedule} and \emph{customer
137e0e7b
EK
876satisfaction} is at the center. From the customers point of view, in addition to
877good usability, \emph{performance} and \emph{lack of bugs} is always
878appreciated, measurements that are also shared by the software developer. (In
879addition, such things as good documentation could be measured, but this is out
880of the scope of this document.)
9a55a5bc 881
00aa0588 882\subsection{The impact on performance}
9a55a5bc 883\begin{quote}
a1bafe90
EK
884 Refactoring certainly will make software go more slowly\footnote{With todays
885 compiler optimization techniques and performance tuning of e.g. the Java
886virtual machine, the penalties of object creation and method calls are
887debatable.}, but it also makes the software more amenable to performance
888tuning.~\cite[p.~69]{refactoring}
9a55a5bc 889\end{quote}
ee45c41f
EK
890
891\noindent There is a common belief that refactoring compromises performance, due
892to increased degree of indirection and that polymorphism is slower than
9a55a5bc
EK
893conditionals.
894
b5c7bb1b 895In a survey, Demeyer\citing{demeyer2002} disproves this view in the case of
a1bafe90 896polymorphism. He did an experiment on, what he calls, ``Transform Self Type
9a55a5bc
EK
897Checks'' where you introduce a new polymorphic method and a new class hierarchy
898to get rid of a class' type checking of a ``type attribute``. He uses this kind
899of transformation to represent other ways of replacing conditionals with
900polymorphism as well. The experiment is performed on the C++ programming
a1bafe90
EK
901language and with three different compilers and platforms. Demeyer concludes
902that, with compiler optimization turned on, polymorphism beats middle to large
903sized if-statements and does as well as case-statements. (In accordance with
904his hypothesis, due to similarities between the way C++ handles polymorphism and
905case-statements.)
ee45c41f 906
9a55a5bc
EK
907\begin{quote}
908 The interesting thing about performance is that if you analyze most programs,
b5c7bb1b 909 you find that they waste most of their time in a small fraction of the
4cb06723 910 code.~\cite[p.~70]{refactoring}
9a55a5bc 911\end{quote}
9a55a5bc 912
ee45c41f
EK
913\noindent So, although an increased amount of method calls could potentially
914slow down programs, one should avoid premature optimization and sacrificing good
fe0a4c48
EK
915design, leaving the performance tuning until after \gloss{profiling} the
916software and having isolated the actual problem areas.
00aa0588 917
0d7fbd88 918\section{Composite refactorings}\label{compositeRefactorings}
f3a108c3
EK
919\todo{motivation, examples, manual vs automated?, what about refactoring in a
920very large code base?}
6065c96c 921Generally, when thinking about refactoring, at the mechanical level, there are
f65da046 922essentially two kinds of refactorings. There are the \emph{primitive}
a1bafe90 923refactorings, and the \emph{composite} refactorings.
6065c96c 924
6c51af15
EK
925\definition{A \emph{primitive refactoring} is a refactoring that cannot be
926expressed in terms of other refactorings.}
f65da046 927
fe0a4c48 928\noindent Examples are the \refa{Pull Up Field} and \refa{Pull Up
a1bafe90 929Method} refactorings\citing{refactoring}, that move members up in their class
ee45c41f
EK
930hierarchies.
931
6c51af15
EK
932\definition{A \emph{composite refactoring} is a refactoring that can be
933expressed in terms of two or more other refactorings.}
f65da046 934
fe0a4c48 935\noindent An example of a composite refactoring is the \refa{Extract
b5c7bb1b
EK
936Superclass} refactoring\citing{refactoring}. In its simplest form, it is composed
937of the previously described primitive refactorings, in addition to the
fe0a4c48 938\refa{Pull Up Constructor Body} refactoring\citing{refactoring}. It works
b5c7bb1b 939by creating an abstract superclass that the target class(es) inherits from, then
fe0a4c48
EK
940by applying \refa{Pull Up Field}, \refa{Pull Up Method} and
941\refa{Pull Up Constructor Body} on the members that are to be members of
f5fb40e4
EK
942the new superclass. If there are multiple classes in play, their interfaces may
943need to be united with the help of some rename refactorings, before extracting
fe0a4c48 944the superclass. For an overview of the \refa{Extract Superclass}
8b6b22c8 945refactoring, see \myref{fig:extractSuperclass}.
6065c96c 946
ddcea0b5
EK
947\begin{figure}[h]
948 \centering
faa9f4f3 949 \includegraphics[angle=270,width=\linewidth]{extractSuperclassItalic.pdf}
f5fb40e4 950 \caption{The Extract Superclass refactoring, with united interfaces.}
ddcea0b5
EK
951 \label{fig:extractSuperclass}
952\end{figure}
6065c96c
EK
953
954\section{Manual vs. automated refactorings}
0d7fbd88 955Refactoring is something every programmer does, even if \heshe does not known
f65da046
EK
956the term \emph{refactoring}. Every refinement of source code that does not alter
957the program's behavior is a refactoring. For small refactorings, such as
0d7fbd88 958\ExtractMethod, executing it manually is a manageable task, but is still prone
a1bafe90 959to errors. Getting it right the first time is not easy, considering the method
f65da046
EK
960signature and all the other aspects of the refactoring that has to be in place.
961
f5fb40e4
EK
962Consider the renaming of classes, methods and fields. For complex programs these
963refactorings are almost impossible to get right. Attacking them with textual
964search and replace, or even regular expressions, will fall short on these tasks.
965Then it is crucial to have proper tool support that can perform them
966automatically. Tools that can parse source code and thus have semantic knowledge
967about which occurrences of which names belong to what construct in the program.
968For even trying to perform one of these complex task manually, one would have to
969be very confident on the existing test suite \see{testing}.
00aa0588 970
19c4f27d 971\section{Correctness of refactorings}\label{correctness}
f65da046 972For automated refactorings to be truly useful, they must show a high degree of
f5fb40e4
EK
973behavior preservation. This last sentence might seem obvious, but there are
974examples of refactorings in existing tools that break programs. In an ideal
975world, every automated refactoring would be ``complete'', in the sense that it
976would never break a program. In an ideal world, every program would also be free
977from bugs. In modern IDEs the implemented automated refactorings are working for
978\emph{most} cases, that is enough for making them useful.
979
980I will now present an example of a \emph{corner case} where a program breaks
981when a refactoring is applied. The example shows an \ExtractMethod refactoring
982followed by a \MoveMethod refactoring that breaks a program in both the
fe0a4c48 983\name{Eclipse} and \name{IntelliJ} IDEs\footnote{The \name{NetBeans} IDE handles this
3ab3e132 984 particular situation without altering the program's behavior, mainly because
fe0a4c48 985 its \refa{Move Method} refactoring implementation is a bit flawed in other ways
f5fb40e4
EK
986 \see{toolSupport}.}. The target and the destination for the composed
987 refactoring is shown in \myref{lst:correctnessExtractAndMove}. Note that the
988 method \method{m(C c)} of class \type{X} assigns to the field \var{x} of the
989 argument \var{c} that has type \type{C}.
990
991\begin{listing}[h]
992\begin{multicols}{2}
993\begin{minted}[linenos]{java}
994// Refactoring target
ddcea0b5 995public class C {
f5fb40e4 996 public X x = new X();
ee45c41f 997
f5fb40e4
EK
998 public void f() {
999 x.m(this);
1000 // Not the same x
1001 x.n();
1002 }
ddcea0b5
EK
1003}
1004\end{minted}
ee45c41f 1005
f5fb40e4 1006\columnbreak
ee45c41f 1007
f5fb40e4
EK
1008\begin{minted}[]{java}
1009// Method destination
ee45c41f 1010public class X {
f5fb40e4
EK
1011 public void m(C c) {
1012 c.x = new X();
1013 // If m is called from
1014 // c, then c.x no longer
1015 // equals 'this'
1016 }
1017 public void n() {}
ee45c41f
EK
1018}
1019\end{minted}
f5fb40e4
EK
1020\end{multicols}
1021\caption{The target and the destination for the composition of the Extract
fe0a4c48 1022Method and \refa{Move Method} refactorings.}
f5fb40e4
EK
1023\label{lst:correctnessExtractAndMove}
1024\end{listing}
ee45c41f 1025
f5fb40e4
EK
1026
1027The refactoring sequence works by extracting line 6 through 8 from the original
3510e539 1028class \type{C} into a method \method{f} with the statements from those lines as
f5fb40e4
EK
1029its method body (but with the comment left out, since it will no longer hold any
1030meaning). The method is then moved to the class \type{X}. The result is shown
1031in \myref{lst:correctnessExtractAndMoveResult}.
ee45c41f 1032
f5fb40e4
EK
1033Before the refactoring, the methods \method{m} and \method{n} of class \type{X}
1034are called on different object instances (see line 6 and 8 of the original class
1035\type{C} in \cref{lst:correctnessExtractAndMove}). After the refactoring, they
1036are called on the same object, and the statement on line
10373 of class \type{X} (in \cref{lst:correctnessExtractAndMoveResult}) no longer
1038 has the desired effect in our example. The method \method{f} of class \type{C}
1039 is now calling the method \method{f} of class \type{X} (see line 5 of class
1040 \type{C} in \cref{lst:correctnessExtractAndMoveResult}), and the program now
1041 behaves different than before.
1042
1043\begin{listing}[h]
1044\begin{multicols}{2}
1045\begin{minted}[linenos]{java}
ee45c41f
EK
1046public class C {
1047 public X x = new X();
1048
1049 public void f() {
1050 x.f(this);
1051 }
1052}
1053\end{minted}
1054
f5fb40e4
EK
1055\columnbreak
1056
1057\begin{minted}[linenos]{java}
ee45c41f
EK
1058public class X {
1059 public void m(C c) {
1060 c.x = new X();
1061 }
1062 public void n() {}
f5fb40e4
EK
1063 // Extracted and
1064 // moved method
ee45c41f
EK
1065 public void f(C c) {
1066 m(c);
1067 n();
1068 }
1069}
1070\end{minted}
f5fb40e4
EK
1071\end{multicols}
1072\caption{The result of the composed refactoring.}
1073\label{lst:correctnessExtractAndMoveResult}
1074\end{listing}
ddcea0b5 1075
aa1e3779
EK
1076The bug introduced in the previous example is of such a nature\footnote{Caused
1077 by aliasing. See \url{https://en.wikipedia.org/wiki/Aliasing_(computing)}}
1078 that it is very difficult to spot if the refactored code is not covered by
1079 tests. It does not generate compilation errors, and will thus only result in
1080 a runtime error or corrupted data, which might be hard to detect.
19c4f27d 1081
29f39f29 1082\section{Refactoring and the importance of testing}\label{testing}
19c4f27d
EK
1083\begin{quote}
1084 If you want to refactor, the essential precondition is having solid
1085 tests.\citing{refactoring}
1086\end{quote}
1087
29f39f29
EK
1088When refactoring, there are roughly three classes of errors that can be made.
1089The first class of errors are the ones that make the code unable to compile.
1090These \emph{compile-time} errors are of the nicer kind. They flash up at the
1091moment they are made (at least when using an IDE), and are usually easy to fix.
1092The second class are the \emph{runtime} errors. Although they take a bit longer
1093to surface, they usually manifest after some time in an illegal argument
1094exception, null pointer exception or similar during the program execution.
1095These kind of errors are a bit harder to handle, but at least they will show,
1096eventually. Then there are the \emph{behavior-changing} errors. These errors are
1097of the worst kind. They do not show up during compilation and they do not turn
1098on a blinking red light during runtime either. The program can seem to work
1099perfectly fine with them in play, but the business logic can be damaged in ways
1100that will only show up over time.
1101
1102For discovering runtime errors and behavior changes when refactoring, it is
1103essential to have good test coverage. Testing in this context means writing
1104automated tests. Manual testing may have its uses, but when refactoring, it is
1105automated unit testing that dominate. For discovering behavior changes it is
1106especially important to have tests that cover potential problems, since these
1107kind of errors does not reveal themselves.
1108
1109Unit testing is not a way to \emph{prove} that a program is correct, but it is a
3ab3e132 1110way to make you confident that it \emph{probably} works as desired. In the
4928aa0b 1111context of test-driven development (commonly known as TDD), the tests are even a
29f39f29
EK
1112way to define how the program is \emph{supposed} to work. It is then, by
1113definition, working if the tests are passing.
19c4f27d
EK
1114
1115If the test coverage for a code base is perfect, then it should, theoretically,
29f39f29
EK
1116be risk-free to perform refactorings on it. This is why automated tests and
1117refactoring are such a great match.
f65da046 1118
b5d53f51 1119\subsection{Testing the code from correctness section}
29f39f29
EK
1120The worst thing that can happen when refactoring is to introduce changes to the
1121behavior of a program, as in the example on \myref{correctness}. This example
1122may be trivial, but the essence is clear. The only problem with the example is
1123that it is not clear how to create automated tests for it, without changing it
1124in intrusive ways.
1125
20bcc7bf 1126Unit tests, as they are known from the different \glosspl{xUnit} around, are
29f39f29
EK
1127only suitable to test the \emph{result} of isolated operations. They can not
1128easily (if at all) observe the \emph{history} of a program.
b5d53f51 1129
a13e5650 1130This problem is still open.
116805bf 1131
a13e5650 1132\begin{comment}
116805bf
EK
1133
1134Assuming a sequential (non-concurrent) program:
1135
1136\begin{minted}{java}
1137tracematch (C c, X x) {
1138 sym m before:
1139 call(* X.m(C)) && args(c) && cflow(within(C));
1140 sym n before:
1141 call(* X.n()) && target(x) && cflow(within(C));
1142 sym setCx after:
1143 set(C.x) && target(c) && !cflow(m);
1144
1145 m n
1146
1147 { assert x == c.x; }
1148}
1149\end{minted}
1150
1151%\begin{minted}{java}
1152%tracematch (X x1, X x2) {
1153% sym m before:
1154% call(* X.m(C)) && target(x1);
1155% sym n before:
1156% call(* X.n()) && target(x2);
1157% sym setX after:
1158% set(C.x) && !cflow(m) && !cflow(n);
1159%
1160% m n
1161%
1162% { assert x1 != x2; }
1163%}
1164%\end{minted}
a13e5650 1165\end{comment}
116805bf 1166
222d172b
EK
1167
1168\chapter{The Project}
1169
0e6e57d3
EK
1170\section{Project description}
1171The aim of this master project will be to explore the relationship between the
1172\ExtractMethod and \MoveMethod refactorings. This will be done by composing the
1173two into a composite refactoring. The refactoring will be called the
1174\ExtractAndMoveMethod refactoring.
b5d53f51 1175
a13e5650
EK
1176The composition of the \ExtractMethod and \MoveMethod refactorings springs
1177naturally out of the need to move procedures closer to the data they manipulate.
1178This composed refactoring is not well described in the literature, but it is
1179implemented in at least one tool called
fe0a4c48
EK
1180\name{CodeRush}\footnote{\url{https://help.devexpress.com/\#CodeRush/CustomDocument3519}},
1181that is an extension for \name{MS Visual
b5d53f51 1182Studio}\footnote{\url{http://www.visualstudio.com/}}. In CodeRush it is called
fe0a4c48 1183\refa{Extract Method to
b5d53f51 1184Type}\footnote{\url{https://help.devexpress.com/\#CodeRush/CustomDocument6710}},
0e6e57d3 1185but I choose to call it \ExtractAndMoveMethod, since I feel this better
b5d53f51
EK
1186communicates which primitive refactorings it is composed of.
1187
0e6e57d3
EK
1188The project will consist in implementing the \ExtractAndMoveMethod refactoring,
1189as well as executing it over a larger code base, as a case study. To be able to
1190execute the refactoring automatically I have to make it analyze code to
1191determine the best selections to extract into new methods.
70905ddc 1192
021508ad
EK
1193\section{The primitive refactorings}
1194The refactorings presented here are the primitive refactorings used in this
1195project. They are the abstract building blocks used by the \ExtractAndMoveMethod
1196refactoring.
04e21f15
EK
1197
1198\subsection{The Extract Method refactoring}
1199The \refa{Extract Method} refactoring is used to extract a fragment of code
1200from its context and into a new method. A call to the new method is inlined
d516ac0b
EK
1201where the fragment was before. It is used to break code into logical units, with
1202names that explain their purpose.
1203
1204An example of an \ExtractMethod refactoring is shown in
1205\myref{lst:extractMethodRefactoring}. It shows a method containing calls to the
1206methods \method{foo} and \method{bar} of a type \type{X}. These statements are
1207then extracted into the new method \method{fooBar}.
d516ac0b 1208
021508ad 1209\begin{listing}[h]
d516ac0b
EK
1210 \begin{multicols}{2}
1211 \begin{minted}[samepage]{java}
1212 // Before
1213 class C {
1214 void method() {
1215 X x = new X();
1216 x.foo(); x.bar();
1217 }
1218 }
1219 \end{minted}
1220
1221 \columnbreak
1222
1223 \begin{minted}[samepage]{java}
1224 // After
1225 class C {
1226 void method() {
1227 X x = new X();
1228 fooBar(x);
1229 }
d516ac0b
EK
1230 void fooBar(X x) {
1231 x.foo(); x.bar();
1232 }
1233 }
1234 \end{minted}
1235 \end{multicols}
1236 \caption{An example of an \ExtractMethod refactoring.}
1237 \label{lst:extractMethodRefactoring}
1238\end{listing}
04e21f15
EK
1239
1240\subsection{The Move Method refactoring}
1241The \refa{Move Method} refactoring is used to move a method from one class to
4306ef44
EK
1242another. This can be appropriate if the method is using more features of another
1243class than of the class which it is currently defined.
1244
1245\Myref{lst:moveMethodRefactoring} shows an example of this refactoring. Here a
1246method \method{fooBar} is moved from the class \type{C} to the class \type{X}.
1247
021508ad 1248\begin{listing}[h]
4306ef44
EK
1249 \begin{multicols}{2}
1250 \begin{minted}[samepage]{java}
1251 // Before
1252 class C {
1253 void method() {
1254 X x = new X();
1255 fooBar(x);
1256 }
1257 void fooBar(X x) {
1258 x.foo(); x.bar();
1259 }
1260 }
1261
1262 class X {
1263 void foo(){/*...*/}
1264 void bar(){/*...*/}
1265 }
1266 \end{minted}
1267
1268 \columnbreak
1269
1270 \begin{minted}[samepage]{java}
1271 // After
1272 class C {
1273 void method() {
1274 X x = new X();
1275 x.fooBar();
1276 }
1277 }
1278
1279 class X {
1280 void fooBar() {
1281 foo(); bar();
1282 }
1283 void foo(){/*...*/}
1284 void bar(){/*...*/}
1285 }
1286 \end{minted}
1287 \end{multicols}
1288 \caption{An example of a \MoveMethod refactoring.}
1289 \label{lst:moveMethodRefactoring}
1290\end{listing}
04e21f15 1291
021508ad
EK
1292\section{The Extract and Move Method refactoring}
1293The \ExtractAndMoveMethod refactoring is a composite refactoring composed of the
1294primitive \ExtractMethod and \MoveMethod refactorings. The effect of this
1295refactoring on source code is the same as when extracting a method and moving it
1296to another class. Conseptually, this is done without an intermediate step. In
1297practice, as we shall see later, an intermediate step may be necessary.
1298
1299An example of this composite refactoring is shown in
1300\myref{lst:extractAndMoveMethodRefactoring}. The example joins the examples from
1301\cref{lst:extractMethodRefactoring} and \cref{lst:moveMethodRefactoring}. This
1302means that the selection consisting of the consecutive calls to the methods
1303\method{foo} and \method{bar}, is extracted into a new method \method{fooBar}
1304located in the class \type{X}.
1305
1306\begin{listing}[h]
1307 \begin{multicols}{2}
1308 \begin{minted}[samepage]{java}
1309 // Before
1310 class C {
1311 void method() {
1312 X x = new X();
1313 x.foo(); x.bar();
1314 }
1315 }
1316
1317 class X {
1318 void foo(){/*...*/}
1319 void bar(){/*...*/}
1320 }
1321 \end{minted}
1322
1323 \columnbreak
1324
1325 \begin{minted}[samepage]{java}
1326 // After
1327 class C {
1328 void method() {
1329 X x = new X();
1330 x.fooBar();
1331 }
1332 }
04e21f15 1333
021508ad
EK
1334 class X {
1335 void fooBar() {
1336 foo(); bar();
1337 }
1338 void foo(){/*...*/}
1339 void bar(){/*...*/}
1340 }
1341 \end{minted}
1342 \end{multicols}
1343 \caption{An example of the \ExtractAndMoveMethod refactoring.}
1344 \label{lst:extractAndMoveMethodRefactoring}
1345\end{listing}
04e21f15 1346
3f929fcc 1347\section{Choosing the target language}
70905ddc
EK
1348Choosing which programming language the code that shall be manipulated shall be
1349written in, is not a very difficult task. We choose to limit the possible
1350languages to the object-oriented programming languages, since most of the
1351terminology and literature regarding refactoring comes from the world of
1352object-oriented programming. In addition, the language must have existing tool
1353support for refactoring.
1354
fe0a4c48 1355The \name{Java} programming language\footnote{\url{https://www.java.com/}} is
70905ddc
EK
1356the dominating language when it comes to example code in the literature of
1357refactoring, and is thus a natural choice. Java is perhaps, currently the most
fe0a4c48 1358influential programming language in the world, with its \name{Java Virtual
70905ddc
EK
1359Machine} that runs on all of the most popular architectures and also supports
1360dozens of other programming languages\footnote{They compile to java bytecode.},
fe0a4c48 1361with \name{Scala}, \name{Clojure} and \name{Groovy} as the most prominent ones.
70905ddc
EK
1362Java is currently the language that every other programming language is compared
1363against. It is also the primary programming language for the author of this
1364thesis.
3f929fcc
EK
1365
1366\section{Choosing the tools}
3ab3e132 1367When choosing a tool for manipulating Java, there are certain criteria that
3f929fcc
EK
1368have to be met. First of all, the tool should have some existing refactoring
1369support that this thesis can build upon. Secondly it should provide some kind of
1370framework for parsing and analyzing Java source code. Third, it should itself be
1371open source. This is both because of the need to be able to browse the code for
1372the existing refactorings that is contained in the tool, and also because open
1373source projects hold value in them selves. Another important aspect to consider
1374is that open source projects of a certain size, usually has large communities of
3ab3e132
EK
1375people connected to them, that are committed to answering questions regarding the
1376use and misuse of the products, that to a large degree is made by the community
3f929fcc
EK
1377itself.
1378
3ab3e132 1379There is a certain class of tools that meet these criteria, namely the class of
3f929fcc 1380\emph{IDEs}\footnote{\emph{Integrated Development Environment}}. These are
3ab3e132 1381programs that is meant to support the whole production cycle of a computer
3f929fcc
EK
1382program, and the most popular IDEs that support Java, generally have quite good
1383refactoring support.
1384
fe0a4c48
EK
1385The main contenders for this thesis is the \name{Eclipse IDE}, with the
1386\name{Java development tools} (JDT), the \name{IntelliJ IDEA Community Edition}
1387and the \name{NetBeans IDE} \see{toolSupport}. \name{Eclipse} and
1388\name{NetBeans} are both free, open source and community driven, while the
1389\name{IntelliJ IDEA} has an open sourced community edition that is free of
1390charge, but also offer an \name{Ultimate Edition} with an extended set of
1391features, at additional cost. All three IDEs supports adding plugins to extend
1392their functionality and tools that can be used to parse and analyze Java source
1393code. But one of the IDEs stand out as a favorite, and that is the \name{Eclipse
1394IDE}. This is the most popular\citing{javaReport2011} among them and seems to be
1395de facto standard IDE for Java development regardless of platform.
4e135659 1396
a5317dcf 1397
5837a41f
EK
1398\chapter{Refactorings in Eclipse JDT: Design, Shortcomings and Wishful
1399Thinking}\label{ch:jdt_refactorings}
1400
1401This chapter will deal with some of the design behind refactoring support in
fe0a4c48 1402\name{Eclipse}, and the JDT in specific. After which it will follow a section about
5837a41f
EK
1403shortcomings of the refactoring API in terms of composition of refactorings. The
1404chapter will be concluded with a section telling some of the ways the
1405implementation of refactorings in the JDT could have worked to facilitate
1406composition of refactorings.
055dca93 1407
b0e80574 1408\section{Design}
fe0a4c48 1409The refactoring world of \name{Eclipse} can in general be separated into two parts: The
b289552b 1410language independent part and the part written for a specific programming
07e173d4
EK
1411language -- the language that is the target of the supported refactorings.
1412\todo{What about the language specific part?}
f041551b
EK
1413
1414\subsection{The Language Toolkit}
1326eec6
EK
1415The Language Toolkit\footnote{The content of this section is a mixture of
1416 written material from
1417 \url{https://www.eclipse.org/articles/Article-LTK/ltk.html} and
1418 \url{http://www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html},
1419the LTK source code and my own memory.}, or LTK for short, is the framework that
fe0a4c48 1420is used to implement refactorings in \name{Eclipse}. It is language independent and
1326eec6
EK
1421provides the abstractions of a refactoring and the change it generates, in the
1422form of the classes \typewithref{org.eclipse.ltk.core.refactoring}{Refactoring}
1423and \typewithref{org.eclipse.ltk.core.refactoring}{Change}.
1424
1425There are also parts of the LTK that is concerned with user interaction, but
1426they will not be discussed here, since they are of little value to us and our
1427use of the framework. We are primarily interested in the parts that can be
1428automated.
f041551b
EK
1429
1430\subsubsection{The Refactoring Class}
1431The abstract class \type{Refactoring} is the core of the LTK framework. Every
1432refactoring that is going to be supported by the LTK have to end up creating an
1433instance of one of its subclasses. The main responsibilities of subclasses of
1434\type{Refactoring} is to implement template methods for condition checking
1435(\methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{checkInitialConditions}
1436and
1437\methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{checkFinalConditions}),
1438in addition to the
1439\methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{createChange}
07e173d4
EK
1440method that creates and returns an instance of the \type{Change} class.
1441
1442If the refactoring shall support that others participate in it when it is
1443executed, the refactoring has to be a processor-based
1444refactoring\typeref{org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring}.
1445It then delegates to its given
1446\typewithref{org.eclipse.ltk.core.refactoring.participants}{RefactoringProcessor}
1326eec6
EK
1447for condition checking and change creation. Participating in a refactoring can
1448be useful in cases where the changes done to programming source code affects
1449other related resources in the workspace. This can be names or paths in
1450configuration files, or maybe one would like to perform additional logging of
1451changes done in the workspace.
f041551b
EK
1452
1453\subsubsection{The Change Class}
07e173d4
EK
1454This class is the base class for objects that is responsible for performing the
1455actual workspace transformations in a refactoring. The main responsibilities for
1456its subclasses is to implement the
1457\methodwithref{org.eclipse.ltk.core.refactoring.Change}{perform} and
1458\methodwithref{org.eclipse.ltk.core.refactoring.Change}{isValid} methods. The
1459\method{isValid} method verifies that the change object is valid and thus can be
1460executed by calling its \method{perform} method. The \method{perform} method
1461performs the desired change and returns an undo change that can be executed to
1462reverse the effect of the transformation done by its originating change object.
1463
61420ef7 1464\subsubsection{Executing a Refactoring}\label{executing_refactoring}
07e173d4
EK
1465The life cycle of a refactoring generally follows two steps after creation:
1466condition checking and change creation. By letting the refactoring object be
1467handled by a
1468\typewithref{org.eclipse.ltk.core.refactoring}{CheckConditionsOperation} that
1469in turn is handled by a
1470\typewithref{org.eclipse.ltk.core.refactoring}{CreateChangeOperation}, it is
1471assured that the change creation process is managed in a proper manner.
1472
1473The actual execution of a change object has to follow a detailed life cycle.
1474This life cycle is honored if the \type{CreateChangeOperation} is handled by a
1475\typewithref{org.eclipse.ltk.core.refactoring}{PerformChangeOperation}. If also
1476an undo manager\typeref{org.eclipse.ltk.core.refactoring.IUndoManager} is set
1477for the \type{PerformChangeOperation}, the undo change is added into the undo
1478history.
055dca93 1479
b0e80574 1480\section{Shortcomings}
80663734 1481This section is introduced naturally with a conclusion: The JDT refactoring
5837a41f
EK
1482implementation does not facilitate composition of refactorings.
1483\todo{refine}This section will try to explain why, and also identify other
1484shortcomings of both the usability and the readability of the JDT refactoring
1485source code.
80663734
EK
1486
1487I will begin at the end and work my way toward the composition part of this
1488section.
1489
5837a41f 1490\subsection{Absence of Generics in Eclipse Source Code}
80663734 1491This section is not only concerning the JDT refactoring API, but also large
fe0a4c48 1492quantities of the \name{Eclipse} source code. The code shows a striking absence of the
80663734 1493Java language feature of generics. It is hard to read a class' interface when
5837a41f
EK
1494methods return objects or takes parameters of raw types such as \type{List} or
1495\type{Map}. This sometimes results in having to read a lot of source code to
1496understand what is going on, instead of relying on the available interfaces. In
1497addition, it results in a lot of ugly code, making the use of typecasting more
1498of a rule than an exception.
1499
1500\subsection{Composite Refactorings Will Not Appear as Atomic Actions}
1501
1502\subsubsection{Missing Flexibility from JDT Refactorings}
1503The JDT refactorings are not made with composition of refactorings in mind. When
1504a JDT refactoring is executed, it assumes that all conditions for it to be
1326eec6 1505applied successfully can be found by reading source files that have been
5837a41f
EK
1506persisted to disk. They can only operate on the actual source material, and not
1507(in-memory) copies thereof. This constitutes a major disadvantage when trying to
1326eec6
EK
1508compose refactorings, since if an exception occurs in the middle of a sequence
1509of refactorings, it can leave the project in a state where the composite
1510refactoring was only partially executed. It makes it hard to discard the changes
5837a41f
EK
1511done without monitoring and consulting the undo manager, an approach that is not
1512bullet proof.
1513
1514\subsubsection{Broken Undo History}
1515When designing a composed refactoring that is to be performed as a sequence of
1516refactorings, you would like it to appear as a single change to the workspace.
1517This implies that you would also like to be able to undo all the changes done by
1518the refactoring in a single step. This is not the way it appears when a sequence
1519of JDT refactorings is executed. It leaves the undo history filled up with
1520individual undo actions corresponding to every single JDT refactoring in the
fe0a4c48 1521sequence. This problem is not trivial to handle in \name{Eclipse}
e123ab03 1522\see{hacking_undo_history}.
5837a41f
EK
1523
1524\section{Wishful Thinking}
3727b75b 1525\todoin{???}
80663734 1526
a7514fbd 1527
b0e80574
EK
1528\chapter{Composite Refactorings in Eclipse}
1529
1530\section{A Simple Ad Hoc Model}
fe0a4c48 1531As pointed out in \myref{ch:jdt_refactorings}, the \name{Eclipse} JDT refactoring model
8b6b22c8
EK
1532is not very well suited for making composite refactorings. Therefore a simple
1533model using changer objects (of type \type{RefaktorChanger}) is used as an
fe0a4c48 1534abstraction layer on top of the existing \name{Eclipse} refactorings, instead of
50954fde
EK
1535extending the \typewithref{org.eclipse.ltk.core.refactoring}{Refactoring} class.
1536
1537The use of an additional abstraction layer is a deliberate choice. It is due to
1538the problem of creating a composite
1539\typewithref{org.eclipse.ltk.core.refactoring}{Change} that can handle text
1540changes that interfere with each other. Thus, a \type{RefaktorChanger} may, or
1541may not, take advantage of one or more existing refactorings, but it is always
1542intended to make a change to the workspace.
1543
1544\subsection{A typical \type{RefaktorChanger}}
1545The typical refaktor changer class has two responsibilities, checking
1546preconditions and executing the requested changes. This is not too different
1547from the responsibilities of an LTK refactoring, with the distinction that a
1548refaktor changer also executes the change, while an LTK refactoring is only
1549responsible for creating the object that can later be used to do the job.
1550
1551Checking of preconditions is typically done by an
1552\typewithref{no.uio.ifi.refaktor.analyze.analyzers}{Analyzer}. If the
1553preconditions validate, the upcoming changes are executed by an
1554\typewithref{no.uio.ifi.refaktor.change.executors}{Executor}.
b0e80574
EK
1555
1556\section{The Extract and Move Method Refactoring}
61420ef7
EK
1557%The Extract and Move Method Refactoring is implemented mainly using these
1558%classes:
1559%\begin{itemize}
1560% \item \type{ExtractAndMoveMethodChanger}
1561% \item \type{ExtractAndMoveMethodPrefixesExtractor}
1562% \item \type{Prefix}
1563% \item \type{PrefixSet}
1564%\end{itemize}
1565
1566\subsection{The Building Blocks}
1567This is a composite refactoring, and hence is built up using several primitive
b5c7bb1b
EK
1568refactorings. These basic building blocks are, as its name implies, the
1569\ExtractMethod refactoring\citing{refactoring} and the \MoveMethod
fe0a4c48 1570refactoring\citing{refactoring}. In \name{Eclipse}, the implementations of these
b5c7bb1b 1571refactorings are found in the classes
61420ef7
EK
1572\typewithref{org.eclipse.jdt.internal.corext.refactoring.code}{ExtractMethodRefactoring}
1573and
1574\typewithref{org.eclipse.jdt.internal.corext.refactoring.structure}{MoveInstanceMethodProcessor},
1575where the last class is designed to be used together with the processor-based
1576\typewithref{org.eclipse.ltk.core.refactoring.participants}{MoveRefactoring}.
1577
1578\subsubsection{The ExtractMethodRefactoring Class}
1579This class is quite simple in its use. The only parameters it requires for
1580construction is a compilation
1581unit\typeref{org.eclipse.jdt.core.ICompilationUnit}, the offset into the source
1582code where the extraction shall start, and the length of the source to be
1583extracted. Then you have to set the method name for the new method together with
50954fde 1584its visibility and some not so interesting parameters.
61420ef7
EK
1585
1586\subsubsection{The MoveInstanceMethodProcessor Class}
fe0a4c48
EK
1587For the \refa{Move Method}, the processor requires a little more advanced input than
1588the class for the \refa{Extract Method}. For construction it requires a method
50954fde
EK
1589handle\typeref{org.eclipse.jdt.core.IMethod} for the method that is to be moved.
1590Then the target for the move have to be supplied as the variable binding from a
1591chosen variable declaration. In addition to this, one have to set some
1592parameters regarding setters/getters, as well as delegation.
61420ef7 1593
50954fde
EK
1594To make a working refactoring from the processor, one have to create a
1595\type{MoveRefactoring} with it.
b0e80574 1596
356782a0 1597\subsection{The ExtractAndMoveMethodChanger}
50954fde 1598
61420ef7 1599The \typewithref{no.uio.ifi.refaktor.changers}{ExtractAndMoveMethodChanger}
50954fde
EK
1600class is a subclass of the class
1601\typewithref{no.uio.ifi.refaktor.changers}{RefaktorChanger}. It is responsible
1602for analyzing and finding the best target for, and also executing, a composition
fe0a4c48 1603of the \refa{Extract Method} and \refa{Move Method} refactorings. This particular changer is
50954fde
EK
1604the one of my changers that is closest to being a true LTK refactoring. It can
1605be reworked to be one if the problems with overlapping changes are resolved. The
1606changer requires a text selection and the name of the new method, or else a
1607method name will be generated. The selection has to be of the type
1608\typewithref{no.uio.ifi.refaktor.utils}{CompilationUnitTextSelection}. This
1609class is a custom extension to
1610\typewithref{org.eclipse.jface.text}{TextSelection}, that in addition to the
1611basic offset, length and similar methods, also carry an instance of the
1612underlying compilation unit handle for the selection.
1613
ae138b9d
EK
1614\subsubsection{The
1615 \type{ExtractAndMoveMethodAnalyzer}}\label{extractAndMoveMethodAnalyzer}
50954fde
EK
1616The analysis and precondition checking is done by the
1617\typewithref{no.uio.ifi.refaktor.analyze.analyzers}{ExtractAnd\-MoveMethodAnalyzer}.
1618First is check whether the selection is a valid selection or not, with respect
1619to statement boundaries and that it actually contains any selections. Then it
1620checks the legality of both extracting the selection and also moving it to
95c0f364
EK
1621another class. This checking of is performed by a range of checkers
1622\see{checkers}. If the selection is approved as legal, it is analyzed to find
1623the presumably best target to move the extracted method to.
50954fde
EK
1624
1625For finding the best suitable target the analyzer is using a
1626\typewithref{no.uio.ifi.refaktor.analyze.collectors}{PrefixesCollector} that
ae138b9d
EK
1627collects all the possible candidate targets for the refactoring. All the
1628non-candidates is found by an
50954fde 1629\typewithref{no.uio.ifi.refaktor.analyze.collectors}{UnfixesCollector} that
b8fce5af 1630collects all the targets that will give some kind of error if used. (For
3ab3e132 1631details about the property collectors, see \myref{propertyCollectors}.) All
b8fce5af 1632prefixes (and unfixes) are represented by a
a6415293
EK
1633\typewithref{no.uio.ifi.refaktor.extractors}{Prefix}, and they are collected
1634into sets of prefixes. The safe prefixes is found by subtracting from the set of
b8fce5af 1635candidate prefixes the prefixes that is enclosing any of the unfixes. A prefix
a6415293
EK
1636is enclosing an unfix if the unfix is in the set of its sub-prefixes. As an
1637example, \texttt{``a.b''} is enclosing \texttt{``a''}, as is \texttt{``a''}. The
1638safe prefixes is unified in a \type{PrefixSet}. If a prefix has only one
1639occurrence, and is a simple expression, it is considered unsuitable as a move
1640target. This occurs in statements such as \texttt{``a.foo()''}. For such
1641statements it bares no meaning to extract and move them. It only generates an
1642extra method and the calling of it.
50954fde 1643
fbaa89ce
EK
1644The most suitable target for the refactoring is found by finding the prefix with
1645the most occurrences. If two prefixes have the same occurrence count, but they
1646differ in length, the longest of them is chosen.
1647
0f6e45f8 1648\todoin{Clean up sections/subsections.}
50954fde 1649
c8088eec
EK
1650\subsubsection{The
1651 \type{ExtractAndMoveMethodExecutor}}\label{extractAndMoveMethodExecutor}
50954fde
EK
1652If the analysis finds a possible target for the composite refactoring, it is
1653executed by an
1654\typewithref{no.uio.ifi.refaktor.change.executors}{ExtractAndMoveMethodExecutor}.
1655It is composed of the two executors known as
1656\typewithref{no.uio.ifi.refaktor.change.executors}{ExtractMethodRefactoringExecutor}
1657and
1658\typewithref{no.uio.ifi.refaktor.change.executors}{MoveMethodRefactoringExecutor}.
1659The \type{ExtractAndMoveMethodExecutor} is responsible for gluing the two
3727b75b 1660together by feeding the \type{MoveMethod\-RefactoringExecutor} with the
222d172b
EK
1661resources needed after executing the extract method refactoring.
1662%\see{postExtractExecution}.
50954fde
EK
1663
1664\subsubsection{The \type{ExtractMethodRefactoringExecutor}}
1665This executor is responsible for creating and executing an instance of the
1666\type{ExtractMethodRefactoring} class. It is also responsible for collecting
1667some post execution resources that can be used to find the method handle for the
1668extracted method, as well as information about its parameters, including the
1669variable they originated from.
1670
1671\subsubsection{The \type{MoveMethodRefactoringExecutor}}
1672This executor is responsible for creating and executing an instance of the
1673\type{MoveRefactoring}. The move refactoring is a processor-based refactoring,
fe0a4c48 1674and for the \refa{Move Method} refactoring it is the \type{MoveInstanceMethodProcessor}
50954fde
EK
1675that is used.
1676
1677The handle for the method to be moved is found on the basis of the information
fe0a4c48 1678gathered after the execution of the \refa{Extract Method} refactoring. The only
50954fde
EK
1679information the \type{ExtractMethodRefactoring} is sharing after its execution,
1680regarding find the method handle, is the textual representation of the new
1681method signature. Therefore it must be parsed, the strings for types of the
1682parameters must be found and translated to a form that can be used to look up
1683the method handle from its type handle. They have to be on the unresolved
1684form.\todo{Elaborate?} The name for the type is found from the original
1685selection, since an extracted method must end up in the same type as the
1686originating method.
1687
fe0a4c48 1688When analyzing a selection prior to performing the \refa{Extract Method} refactoring, a
50954fde
EK
1689target is chosen. It has to be a variable binding, so it is either a field or a
1690local variable/parameter. If the target is a field, it can be used with the
1691\type{MoveInstanceMethodProcessor} as it is, since the extracted method still is
1692in its scope. But if the target is local to the originating method, the target
1693that is to be used for the processor must be among its parameters. Thus the
1694target must be found among the extracted method's parameters. This is done by
1695finding the parameter information object that corresponds to the parameter that
1696was declared on basis of the original target's variable when the method was
1697extracted. (The extracted method must take one such parameter for each local
1698variable that is declared outside the selection that is extracted.) To match the
1699original target with the correct parameter information object, the key for the
1700information object is compared to the key from the original target's binding.
1701The source code must then be parsed to find the method declaration for the
1702extracted method. The new target must be found by searching through the
1703parameters of the declaration and choose the one that has the same type as the
1704old binding from the parameter information object, as well as the same name that
1705is provided by the parameter information object.
1706
1707
356782a0
EK
1708\subsection{The
1709SearchBasedExtractAndMoveMethodChanger}\label{searchBasedExtractAndMoveMethodChanger}
c8088eec
EK
1710The
1711\typewithref{no.uio.ifi.refaktor.change.changers}{SearchBasedExtractAndMoveMethodChanger}
1712is a changer whose purpose is to automatically analyze a method, and execute the
1713\ExtractAndMoveMethod refactoring on it if it is a suitable candidate for the
1714refactoring.
1715
1716First, the \typewithref{no.uio.ifi.refaktor.analyze.analyzers}{SearchBasedExtractAndMoveMethodAnalyzer} is used
1717to analyze the method. If the method is found to be a candidate, the result from
1718the analysis is fed to the \type{ExtractAndMoveMethodExecutor}, whose job is to
1719execute the refactoring \see{extractAndMoveMethodExecutor}.
1720
1721\subsubsection{The SearchBasedExtractAndMoveMethodAnalyzer}
1722This analyzer is responsible for analyzing all the possible text selections of a
1723method and then choose the best result out of the analysis results that is, by
1724the analyzer, considered to be the potential candidates for the Extract and Move
1725Method refactoring.
1726
1727Before the analyzer is able to work with the text selections of a method, it
1728needs to generate them. To do this, it parses the method to obtain a
1729\type{MethodDeclaration} for it \see{astEclipse}. Then there is a statement
1730lists creator that creates statements lists of the different groups of
1731statements in the body of the method declaration. A text selections generator
1732generates text selections of all the statement lists for the analyzer to work
1733with.
1734
1735\paragraph{The statement lists creator}
1736is responsible for generating lists of statements for all the possible levels of
1737statements in the method. The statement lists creator is implemented as an AST
1738visitor \see{astVisitor}. It generates lists of statements by visiting all the
1739blocks in the method declaration and stores their statements in a collection of
1740statement lists. In addition, it visits all of the other statements that can
1741have a statement as a child, such as the different control structures and the
1742labeled statement.
1743
1744The switch statement is the only kind of statement that is not straight forward
1745to obtain the child statements from. It stores all of its children in a flat
1746list. Its switch case statements are included in this list. This means that
1747there are potential statement lists between all of these case statements. The
1748list of statements from a switch statement is therefore traversed, and the
1749statements between the case statements are grouped as separate lists.
1750
1751There is an example of how the statement lists creator would generate lists for
1752a simple method in \myref{lst:statementListsExample}.
1753
1754\begin{listing}[h]
1755\def\charwidth{5.7pt}
1756\def\indent{4*\charwidth}
1757\def\lineheight{\baselineskip}
1758\def\mintedtop{\lineheight}
1759
1760\begin{tikzpicture}[overlay, yscale=-1]
1761 \tikzstyle{overlaybox}=[fill=lightgray,opacity=0.2]
1762 \draw[overlaybox] (0,\mintedtop+\lineheight) rectangle
1763 +(22*\charwidth,10*\lineheight);
1764 \draw[overlaybox] (\indent,\mintedtop+2*\lineheight) rectangle
1765 +(13*\charwidth,\lineheight);
1766 \draw[overlaybox] (2*\indent,\mintedtop+6*\lineheight) rectangle
1767 +(13*\charwidth,2*\lineheight);
1768 \draw[overlaybox] (2*\indent,\mintedtop+9*\lineheight) rectangle
1769 +(13*\charwidth,\lineheight);
1770\end{tikzpicture}
1771\begin{minted}{java}
1772void method() {
1773 if (bool)
1774 b.bar();
1775
1776 switch (val) {
1777 case 1:
1778 b.foo();
1779 c.foo();
1780 default:
1781 c.foo();
1782 }
1783}
1784\end{minted}
1785\caption{Example of how the statement lists creator would group a simple method
1786into lists of statements. Each highlighted rectangle represents a list.}
1787\label{lst:statementListsExample}
1788\end{listing}
1789
1790\paragraph{The text selections generator} generates text selections for each
1791list of statements from the statement lists creator. Conceptually, the generator
ae138b9d
EK
1792generates a text selection for every possible ordered \todo{make clearer}
1793combination of statements in a list. For a list of statements, the boundary
1794statements span out a text selection. This means that there are many different
1795lists that could span out the same selection.
c8088eec
EK
1796
1797In practice, the text selections are calculated by only one traversal of the
1798statement list. There is a set of generated text selections. For each statement,
1799there is created a temporary set of selections, in addition to a text selection
1800based on the offset and length of the statement. This text selection is added to
1801the temporary set. Then the new selection is added with every selection from the
1802set of generated text selections. These new selections are added to the
1803temporary set. Then the temporary set of selections is added to the set of
1804generated text selections. The result of adding two text selections is a new
1805text selection spanned out by the two addends.
1806
0fa64de5
EK
1807\begin{listing}[h]
1808\def\charwidth{5.7pt}
1809\def\indent{4*\charwidth}
1810\def\lineheight{\baselineskip}
1811\def\mintedtop{\lineheight}
1812
1813\begin{tikzpicture}[overlay, yscale=-1]
1814 \tikzstyle{overlaybox}=[fill=lightgray,opacity=0.2]
1815
1816 \draw[overlaybox] (2*\charwidth,\mintedtop) rectangle
1817 +(18*\charwidth,\lineheight);
1818
1819 \draw[overlaybox] (2*\charwidth,\mintedtop+\lineheight) rectangle
1820 +(18*\charwidth,\lineheight);
1821
1822 \draw[overlaybox] (2*\charwidth,\mintedtop+3*\lineheight) rectangle
1823 +(18*\charwidth,\lineheight);
1824
1825 \draw[overlaybox] (\indent-3*\charwidth,\mintedtop) rectangle
1826 +(20*\charwidth,2*\lineheight);
1827
1828 \draw[overlaybox] (3*\charwidth,\mintedtop+\lineheight) rectangle
1829 +(16*\charwidth,3*\lineheight);
1830
1831 \draw[overlaybox] (\indent,\mintedtop) rectangle
1832 +(14*\charwidth,4*\lineheight);
1833\end{tikzpicture}
1834\begin{minted}{java}
1835 statement one;
1836 statement two;
1837 ...
1838 statement k;
1839\end{minted}
1840\caption{Example of how the text selections generator would generate text
1841 selections based on a lists of statements. Each highlighted rectangle
1842represents a text selection.}
1843\label{lst:textSelectionsExample}
1844\end{listing}
021508ad
EK
1845\todoin{fix \myref{lst:textSelectionsExample}? Text only? All
1846sub-sequences\ldots}
0fa64de5 1847
ae138b9d
EK
1848\paragraph{Finding the candidate} for the refactoring is done by analyzing all
1849the generated text selection with the \type{ExtractAndMoveMethodAnalyzer}
1850\see{extractAndMoveMethodAnalyzer}. If the analyzer generates a useful result,
1851an \type{ExtractAndMoveMethodCandidate} is created from it, that is kept in a
1852list of potential candidates. If no candidates are found, the
1853\type{NoTargetFoundException} is thrown.
1854
1855Since only one of the candidates can be chosen, the analyzer must sort out which
1856candidate to choose. The sorting is done by the static \method{sort} method of
1857\type{Collections}. The comparison in this sorting is done by an
1858\type{ExtractAndMoveMethodCandidateComparator}.
1859\todoin{Write about the
1860ExtractAndMoveMethodCandidateComparator/FavorNoUnfixesCandidateComparator}
1861
1862\paragraph{The complexity} of how many text selections that needs to be analyzed
1863for a total of $n$ statements is bounded by $O(n^2)$.
1864
3471cd15 1865\begin{theorem}
ae138b9d
EK
1866The number of text selections that need to be analyzed for each list of
1867statements of length $n$, is exactly
1868
3471cd15 1869\begin{equation*}
ae138b9d
EK
1870 \sum_{i=1}^{n} i = \frac{n(n+1)}{2}
1871 \label{eq:complexityStatementList}
3471cd15
EK
1872\end{equation*}
1873\label{thm:numberOfTextSelection}
1874\end{theorem}
ae138b9d
EK
1875
1876\begin{proof}
1877 For $n=1$ this is trivial: $\frac{1(1+1)}{2} = \frac{2}{2} = 1$. One statement
1878 equals one selection.
1879
1880 For $n=2$, you get one text selection for the first statement. For the second,
1881 you get one selection for the statement itself, and one selection for the two
1882 of them combined. This equals three selections. $\frac{2(2+1)}{2} =
1883 \frac{6}{2} = 3$.
1884
1885 For $n=3$, you get 3 selections for the two first statements, as in the case
1886 where $n=2$. In addition you get one selection for the third statement itself,
1887 and two more statements for the combinations of it with the two previous
1888 statements. This equals six selections. $\frac{3(3+1)}{2} = \frac{12}{2} = 6$.
1889
1890 Assume that for $n=k$ there exists $\frac{k(k+1)}{2}$ text selections. Then we
1891 want to add selections for another statement, following the previous $k$
1892 statements. So, for $n=k+1$, we get one additional selection for the statement
1893 itself. Then we get one selection for each pair of the new selection and the
1894 previous $k$ statements. So the total number of selections will be the number
1895 of already generated selections, plus $k$ for every pair, plus one for the
1896 statement itself: $\frac{k(k+1)}{2} + k +
1897 1 = \frac{k(k+1)+2k+2}{2} = \frac{k(k+1)+2(k+1)}{2} = \frac{(k+1)(k+2)}{2} =
1898 \frac{(k+1)((k+1)+1)}{2} = \sum_{i=1}^{k+1} i$
1899\end{proof}
1900
3471cd15
EK
1901\begin{theorem}
1902 The number of text selections for a body of statements is maximized if all the
1903 statements are at the same level.
1904 \label{thm:textSelectionsMaximized}
1905\end{theorem}
1906
1907\begin{proof}
3ab3e132 1908 Assume we have a body of, in total, $k$ statements. Let
3471cd15
EK
1909 $l,\cdots,m,(k-l-\cdots-m)$ be the lengths of the lists of statements in the
1910 body, with $l+\cdots+m<k \Rightarrow l,\cdots,m<k$.
1911
1912 Then, the number of text selections that are generated for the $k$ statements
1913 is
1914
1915 {
1916 \small
1917 \begin{align*}
1918 \frac{(k-l-\cdots-m)((k-l-\cdots-m)+ 1)}{2} + \frac{l(l+1)}{2} + \cdots +
1919 \frac{m(m+1)}{2} = \\
1920 \frac{k^2 - 2kl - \cdots - 2km + l^2 + \cdots + m^2 + k - l - \cdots - m}{2}
1921 + \frac{l^2+l}{2} + \cdots + \frac{m^2+m}{2} = \\
1922 \frac{k^2 + k + 2l^2 - 2kl + \cdots + 2m^2 - 2km}{2}
1923 \end{align*}
1924 }
1925
1926 It then remains to show that this inequality holds:
1927
1928 \begin{align*}
1929 \frac{k^2 + k + 2l^2 - 2kl + \cdots + 2m^2 - 2km}{2} < \frac{k(k+1)}{2} =
1930 \frac{k^2 + k}{2}
1931 \end{align*}
1932
1933 By multiplication by $2$ on both sides, and by removing the equal parts, we get
1934
1935 \begin{align*}
1936 2l^2 - 2kl + \cdots + 2m^2 - 2km < 0
1937 \end{align*}
1938
1939 Since $l,\cdots,m<k$, we have that $\forall i \in \{l,\cdots,m\} : 2ki > 2i^2$,
1940 so all the pairs of parts on the form $2i^2-2ki$ are negative. In sum, the
1941 inequality holds.
1942
1943\end{proof}
ae138b9d
EK
1944
1945Therefore, the complexity for the number of selections that needs to be analyzed
3471cd15 1946for a body of $n$ statements is $O\bigl(\frac{n(n+1)}{2}\bigr) = O(n^2)$.
c8088eec 1947
356782a0 1948
222d172b 1949\begin{comment}
50954fde 1950\subsection{Finding the IMethod}\label{postExtractExecution}
356782a0 1951\todoin{Rename section. Write??}
222d172b 1952\end{comment}
61420ef7 1953
61420ef7 1954
b0e80574 1955\subsection{The Prefix Class}
a6415293
EK
1956This class exists mainly for holding data about a prefix, such as the expression
1957that the prefix represents and the occurrence count of the prefix within a
1958selection. In addition to this, it has some functionality such as calculating
1959its sub-prefixes and intersecting it with another prefix. The definition of the
1960intersection between two prefixes is a prefix representing the longest common
1961expression between the two.
1962
b0e80574 1963\subsection{The PrefixSet Class}
a6415293
EK
1964A prefix set holds elements of type \type{Prefix}. It is implemented with the
1965help of a \typewithref{java.util}{HashMap} and contains some typical set
1966operations, but it does not implement the \typewithref{java.util}{Set}
1967interface, since the prefix set does not need all of the functionality a
1968\type{Set} requires to be implemented. In addition It needs some other
1969functionality not found in the \type{Set} interface. So due to the relatively
1970limited use of prefix sets, and that it almost always needs to be referenced as
1971such, and not a \type{Set<Prefix>}, it remains as an ad hoc solution to a
1972concrete problem.
1973
1974There are two ways adding prefixes to a \type{PrefixSet}. The first is through
1975its \method{add} method. This works like one would expect from a set. It adds
1976the prefix to the set if it does not already contain the prefix. The other way
1977is to \emph{register} the prefix with the set. When registering a prefix, if the
1978set does not contain the prefix, it is just added. If the set contains the
1979prefix, its count gets incremented. This is how the occurrence count is handled.
1980
1981The prefix set also computes the set of prefixes that is not enclosing any
1982prefixes of another set. This is kind of a set difference operation only for
1983enclosing prefixes.
b0e80574 1984
5837a41f
EK
1985\subsection{Hacking the Refactoring Undo
1986History}\label{hacking_undo_history}
a6415293 1987\todoin{Where to put this section?}
8fae7b44
EK
1988
1989As an attempt to make multiple subsequent changes to the workspace appear as a
1990single action (i.e. make the undo changes appear as such), I tried to alter
1991the undo changes\typeref{org.eclipse.ltk.core.refactoring.Change} in the history
1992of the refactorings.
1993
1994My first impulse was to remove the, in this case, last two undo changes from the
f041551b 1995undo manager\typeref{org.eclipse.ltk.core.refactoring.IUndoManager} for the
fe0a4c48 1996\name{Eclipse} refactorings, and then add them to a composite
8fae7b44
EK
1997change\typeref{org.eclipse.ltk.core.refactoring.CompositeChange} that could be
1998added back to the manager. The interface of the undo manager does not offer a
1999way to remove/pop the last added undo change, so a possible solution could be to
4cb06723
EK
2000decorate\citing{designPatterns} the undo manager, to intercept and collect the
2001undo changes before delegating to the \method{addUndo}
f041551b 2002method\methodref{org.eclipse.ltk.core.refactoring.IUndoManager}{addUndo} of the
8fae7b44
EK
2003manager. Instead of giving it the intended undo change, a null change could be
2004given to prevent it from making any changes if run. Then one could let the
2005collected undo changes form a composite change to be added to the manager.
2006
2007There is a technical challenge with this approach, and it relates to the undo
2008manager, and the concrete implementation
2009UndoManager2\typeref{org.eclipse.ltk.internal.core.refactoring.UndoManager2}.
2010This implementation is designed in a way that it is not possible to just add an
2011undo change, you have to do it in the context of an active
2012operation\typeref{org.eclipse.core.commands.operations.TriggeredOperations}.
2013One could imagine that it might be possible to trick the undo manager into
2014believing that you are doing a real change, by executing a refactoring that is
2015returning a kind of null change that is returning our composite change of undo
2016refactorings when it is performed.
2017
2018Apart from the technical problems with this solution, there is a functional
2019problem: If it all had worked out as planned, this would leave the undo history
2020in a dirty state, with multiple empty undo operations corresponding to each of
2021the sequentially executed refactoring operations, followed by a composite undo
2022change corresponding to an empty change of the workspace for rounding of our
2023composite refactoring. The solution to this particular problem could be to
2024intercept the registration of the intermediate changes in the undo manager, and
2025only register the last empty change.
2026
2027Unfortunately, not everything works as desired with this solution. The grouping
2028of the undo changes into the composite change does not make the undo operation
2029appear as an atomic operation. The undo operation is still split up into
2030separate undo actions, corresponding to the change done by its originating
2031refactoring. And in addition, the undo actions has to be performed separate in
2032all the editors involved. This makes it no solution at all, but a step toward
2033something worse.
2034
2035There might be a solution to this problem, but it remains to be found. The
2036design of the refactoring undo management is partly to be blamed for this, as it
2037it is to complex to be easily manipulated.
2038
b0e80574 2039
0d7fbd88 2040
2f2080fb 2041
03674629 2042\chapter{Analyzing Source Code in Eclipse}
5308274d 2043
356782a0 2044\section{The Java model}\label{javaModel}
fe0a4c48 2045The Java model of \name{Eclipse} is its internal representation of a Java project. It
5308274d 2046is light-weight, and has only limited possibilities for manipulating source
fe0a4c48 2047code. It is typically used as a basis for the Package Explorer in \name{Eclipse}.
5308274d
EK
2048
2049The elements of the Java model is only handles to the underlying elements. This
2050means that the underlying element of a handle does not need to actually exist.
2051Hence the user of a handle must always check that it exist by calling the
2052\method{exists} method of the handle.
2053
356782a0 2054The handles with descriptions is listed in \myref{tab:javaModel}.
4e468834
EK
2055
2056\begin{table}[h]
2057 \centering
2058
2059 \newcolumntype{L}[1]{>{\hsize=#1\hsize\raggedright\arraybackslash}X}%
2060 % sum must equal number of columns (3)
2061 \begin{tabularx}{\textwidth}{| L{0.7} | L{1.1} | L{1.2} |}
2062 \hline
2063 \textbf{Project Element} & \textbf{Java Model element} &
2064 \textbf{Description} \\
2065 \hline
2066 Java project & \type{IJavaProject} & The Java project which contains all other objects. \\
2067 \hline
2068 Source folder /\linebreak[2] binary folder /\linebreak[3] external library &
2069 \type{IPackageFragmentRoot} & Hold source or binary files, can be a folder
2070 or a library (zip / jar file). \\
2071 \hline
2072 Each package & \type{IPackageFragment} & Each package is below the
2073 \type{IPackageFragmentRoot}, sub-packages are not leaves of the package,
2074 they are listed directed under \type{IPackageFragmentRoot}. \\
2075 \hline
2076 Java Source file & \type{ICompilationUnit} & The Source file is always below
2077 the package node. \\
2078 \hline
2079 Types /\linebreak[2] Fields /\linebreak[3] Methods & \type{IType} /
2080 \linebreak[0]
2081 \type{IField} /\linebreak[3] \type{IMethod} & Types, fields and methods. \\
2082 \hline
2083 \end{tabularx}
051cf433
EK
2084 \caption{The elements of the Java Model. {\footnotesize Taken from
2085 \url{http://www.vogella.com/tutorials/EclipseJDT/article.html}}}
356782a0 2086 \label{tab:javaModel}
4e468834
EK
2087\end{table}
2088
2089The hierarchy of the Java Model is shown in \myref{fig:javaModel}.
2090
5308274d
EK
2091\begin{figure}[h]
2092 \centering
2093 \begin{tikzpicture}[%
2094 grow via three points={one child at (0,-0.7) and
2095 two children at (0,-0.7) and (0,-1.4)},
2096 edge from parent path={(\tikzparentnode.south west)+(0.5,0) |-
2097 (\tikzchildnode.west)}]
2098 \tikzstyle{every node}=[draw=black,thick,anchor=west]
2099 \tikzstyle{selected}=[draw=red,fill=red!30]
2100 \tikzstyle{optional}=[dashed,fill=gray!50]
2101 \node {\type{IJavaProject}}
2102 child { node {\type{IPackageFragmentRoot}}
2103 child { node {\type{IPackageFragment}}
2104 child { node {\type{ICompilationUnit}}
2105 child { node {\type{IType}}
2106 child { node {\type{\{ IType \}*}}
2107 child { node {\type{\ldots}}}
2108 }
2109 child [missing] {}
2110 child { node {\type{\{ IField \}*}}}
2111 child { node {\type{IMethod}}
2112 child { node {\type{\{ IType \}*}}
2113 child { node {\type{\ldots}}}
2114 }
2115 }
2116 child [missing] {}
2117 child [missing] {}
2118 child { node {\type{\{ IMethod \}*}}}
2119 }
2120 child [missing] {}
2121 child [missing] {}
2122 child [missing] {}
2123 child [missing] {}
2124 child [missing] {}
2125 child [missing] {}
2126 child [missing] {}
2127 child { node {\type{\{ IType \}*}}}
2128 }
2129 child [missing] {}
2130 child [missing] {}
2131 child [missing] {}
2132 child [missing] {}
2133 child [missing] {}
2134 child [missing] {}
2135 child [missing] {}
2136 child [missing] {}
2137 child [missing] {}
2138 child { node {\type{\{ ICompilationUnit \}*}}}
2139 }
2140 child [missing] {}
2141 child [missing] {}
2142 child [missing] {}
2143 child [missing] {}
2144 child [missing] {}
2145 child [missing] {}
2146 child [missing] {}
2147 child [missing] {}
2148 child [missing] {}
2149 child [missing] {}
2150 child [missing] {}
2151 child { node {\type{\{ IPackageFragment \}*}}}
2152 }
2153 child [missing] {}
2154 child [missing] {}
2155 child [missing] {}
2156 child [missing] {}
2157 child [missing] {}
2158 child [missing] {}
2159 child [missing] {}
2160 child [missing] {}
2161 child [missing] {}
2162 child [missing] {}
2163 child [missing] {}
2164 child [missing] {}
2165 child [missing] {}
2166 child { node {\type{\{ IPackageFragmentRoot \}*}}}
2167 ;
2168 \end{tikzpicture}
fe0a4c48 2169 \caption{The Java model of \name{Eclipse}. ``\type{\{ SomeElement \}*}'' means
5308274d
EK
2170 \type{SomeElement} zero or more times. For recursive structures,
2171 ``\type{\ldots}'' is used.}
2172 \label{fig:javaModel}
2173\end{figure}
2174
3ab3e132 2175\section{The Abstract Syntax Tree}
fe0a4c48 2176\name{Eclipse} is following the common paradigm of using an abstract syntax tree for
03674629
EK
2177source code analysis and manipulation.
2178
03674629
EK
2179When parsing program source code into something that can be used as a foundation
2180for analysis, the start of the process follows the same steps as in a compiler.
3ab3e132 2181This is all natural, because the way a compiler analyzes code is no different
03674629
EK
2182from how source manipulation programs would do it, except for some properties of
2183code that is analyzed in the parser, and that they may be differing in what
4e468834 2184kinds of properties they analyze. Thus the process of translation source code
03674629 2185into a structure that is suitable for analyzing, can be seen as a kind of
65e213db
EK
2186interrupted compilation process \see{fig:interruptedCompilationProcess}.
2187
2188\begin{figure}[h]
2189 \centering
2190 \tikzset{
c876d1a4 2191 base/.style={anchor=north, align=center, rectangle, minimum height=1.4cm},
65e213db 2192 basewithshadow/.style={base, drop shadow, fill=white},
c876d1a4
EK
2193 outlined/.style={basewithshadow, draw, rounded corners, minimum
2194 width=0.4cm},
2195 primary/.style={outlined, font=\bfseries},
65e213db 2196 dashedbox/.style={outlined, dashed},
62563950
EK
2197 arrowpath/.style={black, align=center, font=\small},
2198 processarrow/.style={arrowpath, ->, >=angle 90, shorten >=1pt},
65e213db 2199 }
62563950 2200 \begin{tikzpicture}[node distance=1.3cm and 3cm, scale=1, every
c876d1a4 2201 node/.style={transform shape}]
62563950
EK
2202 \node[base](AuxNode1){\small source code};
2203 \node[primary, right=of AuxNode1, xshift=-2.5cm](Scanner){Scanner};
c876d1a4 2204 \node[primary, right=of Scanner, xshift=0.5cm](Parser){Parser};
72e039dc
EK
2205 \node[dashedbox, below=of Parser](SemanticAnalyzer){Semantic\\Analyzer};
2206 \node[dashedbox, left=of SemanticAnalyzer](SourceCodeOptimizer){Source
2207 Code\\Optimizer};
2208 \node[dashedbox, below=of SourceCodeOptimizer
c876d1a4 2209 ](CodeGenerator){Code\\Generator};
72e039dc
EK
2210 \node[dashedbox, right=of CodeGenerator](TargetCodeOptimizer){Target
2211 Code\\Optimizer};
2212 \node[base, right=of TargetCodeOptimizer](AuxNode2){};
c876d1a4 2213
62563950
EK
2214 \draw[processarrow](AuxNode1) -- (Scanner);
2215
2216 \path[arrowpath] (Scanner) -- node [sloped](tokens){tokens}(Parser);
2217 \draw[processarrow](Scanner) -- (tokens) -- (Parser);
2218
2219 \path[arrowpath] (Parser) -- node (syntax){syntax
2220 tree}(SemanticAnalyzer);
2221 \draw[processarrow](Parser) -- (syntax) -- (SemanticAnalyzer);
2222
2223 \path[arrowpath] (SemanticAnalyzer) -- node
2224 [sloped](annotated){annotated\\tree}(SourceCodeOptimizer);
2225 \draw[processarrow, dashed](SemanticAnalyzer) -- (annotated) --
2226 (SourceCodeOptimizer);
2227
2228 \path[arrowpath] (SourceCodeOptimizer) -- node
2229 (intermediate){intermediate code}(CodeGenerator);
2230 \draw[processarrow, dashed](SourceCodeOptimizer) -- (intermediate) --
2231 (CodeGenerator);
2232
2233 \path[arrowpath] (CodeGenerator) -- node [sloped](target1){target
c876d1a4 2234 code}(TargetCodeOptimizer);
62563950
EK
2235 \draw[processarrow, dashed](CodeGenerator) -- (target1) --
2236 (TargetCodeOptimizer);
2237
2238 \path[arrowpath](TargetCodeOptimizer) -- node [sloped](target2){target
c876d1a4 2239 code}(AuxNode2);
62563950 2240 \draw[processarrow, dashed](TargetCodeOptimizer) -- (target2) (AuxNode2);
65e213db 2241 \end{tikzpicture}
72e039dc 2242 \caption{Interrupted compilation process. {\footnotesize (Full compilation
52da2102
EK
2243 process borrowed from \emph{Compiler construction: principles and practice}
2244 by Kenneth C. Louden\citing{louden1997}.)}}
65e213db
EK
2245 \label{fig:interruptedCompilationProcess}
2246\end{figure}
2247
03674629
EK
2248The process starts with a \emph{scanner}, or lexer. The job of the scanner is to
2249read the source code and divide it into tokens for the parser. Therefore, it is
2250also sometimes called a tokenizer. A token is a logical unit, defined in the
2251language specification, consisting of one or more consecutive characters. In
3ab3e132 2252the Java language the tokens can for instance be the \var{this} keyword, a curly
03674629 2253bracket \var{\{} or a \var{nameToken}. It is recognized by the scanner on the
3ab3e132 2254basis of something equivalent of a regular expression. This part of the process
03674629
EK
2255is often implemented with the use of a finite automata. In fact, it is common to
2256specify the tokens in regular expressions, that in turn is translated into a
2257finite automata lexer. This process can be automated.
2258
3ab3e132 2259The program component used to translate a stream of tokens into something
03674629
EK
2260meaningful, is called a parser. A parser is fed tokens from the scanner and
2261performs an analysis of the structure of a program. It verifies that the syntax
2262is correct according to the grammar rules of a language, that is usually
2263specified in a context-free grammar, and often in a variant of the
fe0a4c48 2264\name{Backus--Naur
03674629
EK
2265Form}\footnote{\url{https://en.wikipedia.org/wiki/Backus-Naur\_Form}}. The
2266result coming from the parser is in the form of an \emph{Abstract Syntax Tree},
2267AST for short. It is called \emph{abstract}, because the structure does not
2268contain all of the tokens produced by the scanner. It only contain logical
2269constructs, and because it forms a tree, all kinds of parentheses and brackets
2270are implicit in the structure. It is this AST that is used when performing the
2271semantic analysis of the code.
2272
2273As an example we can think of the expression \code{(5 + 7) * 2}. The root of
fe0a4c48 2274this tree would in \name{Eclipse} be an \type{InfixExpression} with the operator
d11bcf4d
EK
2275\var{TIMES}, and a left operand that is also an \type{InfixExpression} with the
2276operator \var{PLUS}. The left operand \type{InfixExpression}, has in turn a left
2277operand of type \type{NumberLiteral} with the value \var{``5''} and a right
2278operand \type{NumberLiteral} with the value \var{``7''}. The root will have a
2279right operand of type \type{NumberLiteral} and value \var{``2''}. The AST for
2280this expression is illustrated in \myref{fig:astInfixExpression}.
2281
3ab3e132
EK
2282Contrary to the Java Model, an abstract syntax tree is a heavy-weight
2283representation of source code. It contains information about properties like
2284type bindings for variables and variable bindings for names.
4e468834
EK
2285
2286
d11bcf4d
EK
2287\begin{figure}[h]
2288 \centering
a1d68d95 2289 \begin{tikzpicture}[scale=0.8]
894dce0d 2290 \tikzset{level distance=40pt}
a1d68d95
EK
2291 \tikzset{sibling distance=5pt}
2292 \tikzstyle{thescale}=[scale=0.8]
2293 \tikzset{every tree node/.style={align=center}}
d11bcf4d 2294 \tikzset{edge from parent/.append style={thick}}
a1d68d95
EK
2295 \tikzstyle{inode}=[rectangle,rounded corners,draw,fill=lightgray,drop
2296 shadow,align=center]
2297 \tikzset{every internal node/.style={inode}}
894dce0d 2298 \tikzset{every leaf node/.style={draw=none,fill=none}}
d11bcf4d 2299
894dce0d
EK
2300 \Tree [.\type{InfixExpression} [.\type{InfixExpression}
2301 [.\type{NumberLiteral} \var{``5''} ] [.\type{Operator} \var{PLUS} ]
2302 [.\type{NumberLiteral} \var{``7''} ] ]
d11bcf4d
EK
2303 [.\type{Operator} \var{TIMES} ]
2304 [.\type{NumberLiteral} \var{``2''} ]
2305 ]
2306 \end{tikzpicture}
894dce0d 2307 \caption{The abstract syntax tree for the expression \code{(5 + 7) * 2}.}
d11bcf4d
EK
2308 \label{fig:astInfixExpression}
2309\end{figure}
03674629 2310
c8088eec 2311\subsection{The AST in Eclipse}\label{astEclipse}
fe0a4c48 2312In \name{Eclipse}, every node in the AST is a child of the abstract superclass
03674629
EK
2313\typewithref{org.eclipse.jdt.core.dom}{ASTNode}. Every \type{ASTNode}, among a
2314lot of other things, provides information about its position and length in the
2315source code, as well as a reference to its parent and to the root of the tree.
2316
2317The root of the AST is always of type \type{CompilationUnit}. It is not the same
2318as an instance of an \type{ICompilationUnit}, which is the compilation unit
894dce0d 2319handle of the Java model. The children of a \type{CompilationUnit} is an
03674629
EK
2320optional \type{PackageDeclaration}, zero or more nodes of type
2321\type{ImportDecaration} and all its top-level type declarations that has node
2322types \type{AbstractTypeDeclaration}.
2323
2324An \type{AbstractType\-Declaration} can be one of the types
2325\type{AnnotationType\-Declaration}, \type{Enum\-Declaration} or
2326\type{Type\-Declaration}. The children of an \type{AbstractType\-Declaration}
2327must be a subtype of a \type{BodyDeclaration}. These subtypes are:
2328\type{AnnotationTypeMember\-Declaration}, \type{EnumConstant\-Declaration},
2329\type{Field\-Declaration}, \type{Initializer} and \type{Method\-Declaration}.
2330
2331Of the body declarations, the \type{Method\-Declaration} is the most interesting
2332one. Its children include lists of modifiers, type parameters, parameters and
2333exceptions. It has a return type node and a body node. The body, if present, is
2334of type \type{Block}. A \type{Block} is itself a \type{Statement}, and its
2335children is a list of \type{Statement} nodes.
2336
2337There are too many types of the abstract type \type{Statement} to list up, but
2338there exists a subtype of \type{Statement} for every statement type of Java, as
2339one would expect. This also applies to the abstract type \type{Expression}.
2340However, the expression \type{Name} is a little special, since it is both used
2341as an operand in compound expressions, as well as for names in type declarations
2342and such.
2343
fe0a4c48 2344There is an overview of some of the structure of an \name{Eclipse} AST in
94deee9e
EK
2345\myref{fig:astEclipse}.
2346
e8173df5
EK
2347\begin{figure}[h]
2348 \centering
5e5908eb 2349 \begin{tikzpicture}[scale=0.8]
0f918507
EK
2350 \tikzset{level distance=50pt}
2351 \tikzset{sibling distance=5pt}
5e5908eb 2352 \tikzstyle{thescale}=[scale=0.8]
e8173df5 2353 \tikzset{every tree node/.style={align=center}}
5e5908eb
EK
2354 \tikzset{edge from parent/.append style={thick}}
2355 \tikzstyle{inode}=[rectangle,rounded corners,draw,fill=lightgray,drop
2356 shadow,align=center]
2357 \tikzset{every internal node/.style={inode}}
e8173df5
EK
2358 \tikzset{every leaf node/.style={draw=none,fill=none}}
2359
e601ce99
EK
2360 \Tree [.\type{CompilationUnit} [.\type{[ PackageDeclaration ]} [.\type{Name} ]
2361 [.\type{\{ Annotation \}*} ] ]
2362 [.\type{\{ ImportDeclaration \}*} [.\type{Name} ] ]
0f918507 2363 [.\type{\{ AbstractTypeDeclaration \}+} [.\node(site){\type{\{
e601ce99 2364 BodyDeclaration \}*}}; ] [.\type{SimpleName} ] ]
e8173df5 2365 ]
e601ce99 2366 \begin{scope}[shift={(0.5,-6)}]
5e5908eb 2367 \node[inode,thescale](root){\type{MethodDeclaration}};
e601ce99 2368 \node[inode,thescale](modifiers) at (4.5,-5){\type{\{ IExtendedModifier \}*}
5e5908eb 2369 \\ {\footnotesize (Of type \type{Modifier} or \type{Annotation})}};
e601ce99 2370 \node[inode,thescale](typeParameters) at (-6,-3.5){\type{\{ TypeParameter
5e5908eb 2371 \}*}};
fbeec228 2372 \node[inode,thescale](parameters) at (-5,-5){\type{\{
5e5908eb 2373 SingleVariableDeclaration \}*} \\ {\footnotesize (Parameters)}};
e601ce99 2374 \node[inode,thescale](exceptions) at (5,-3){\type{\{ Name \}*} \\
5e5908eb 2375 {\footnotesize (Exceptions)}};
e601ce99 2376 \node[inode,thescale](return) at (-6.5,-2){\type{Type} \\ {\footnotesize
5e5908eb 2377 (Return type)}};
e601ce99
EK
2378 \begin{scope}[shift={(0,-5)}]
2379 \Tree [.\node(body){\type{[ Block ]} \\ {\footnotesize (Body)}};
2380 [.\type{\{ Statement \}*} [.\type{\{ Expression \}*} ]
2381 [.\type{\{ Statement \}*} [.\type{\ldots} ]]
2382 ]
2383 ]
2384 \end{scope}
0f918507 2385 \end{scope}
e601ce99
EK
2386 \draw[->,>=triangle 90,shorten >=1pt](root.east)..controls +(east:2) and
2387 +(south:1)..(site.south);
0f918507 2388
5e5908eb
EK
2389 \draw (root.south) -- (modifiers);
2390 \draw (root.south) -- (typeParameters);
2391 \draw (root.south) -- ($ (parameters.north) + (2,0) $);
2392 \draw (root.south) -- (exceptions);
2393 \draw (root.south) -- (return);
2394 \draw (root.south) -- (body);
2395
e8173df5 2396 \end{tikzpicture}
fe0a4c48 2397 \caption{The format of the abstract syntax tree in \name{Eclipse}.}
e8173df5
EK
2398 \label{fig:astEclipse}
2399\end{figure}
94deee9e 2400\todoin{Add more to the AST format tree? \myref{fig:astEclipse}}
a2868580 2401
b8fce5af 2402\section{The ASTVisitor}\label{astVisitor}
3ab3e132
EK
2403So far, the only thing that has been addressed is how the data that is going to
2404be the basis for our analysis is structured. Another aspect of it is how we are
2405going to traverse the AST to gather the information we need, so we can conclude
2406about the properties we are analysing. It is of course possible to start at the
2407top of the tree, and manually search through its nodes for the ones we are
2408looking for, but that is a bit inconvenient. To be able to efficiently utilize
2409such an approach, we would need to make our own framework for traversing the
2410tree and visiting only the types of nodes we are after. Luckily, this
fe0a4c48 2411functionality is already provided in \name{Eclipse}, by its
50976f51
EK
2412\typewithref{org.eclipse.jdt.core.dom}{ASTVisitor}.
2413
fe0a4c48
EK
2414The \name{Eclipse} AST, together with its \type{ASTVisitor}, follows the
2415\pattern{Visitor} pattern\citing{designPatterns}. The intent of this design
2416pattern is to facilitate extending the functionality of classes without touching
2417the classes themselves.
0a8ca90c 2418
fe0a4c48
EK
2419Let us say that there is a class hierarchy of elements. These elements all have
2420a method \method{accept(Visitor visitor)}. In its simplest form, the
0a8ca90c
EK
2421\method{accept} method just calls the \method{visit} method of the visitor with
2422itself as an argument, like this: \code{visitor.visit(this)}. For the visitors
2423to be able to extend the functionality of all the classes in the elements
2424hierarchy, each \type{Visitor} must have one visit method for each concrete
2425class in the hierarchy. Say the hierarchy consists of the concrete classes
2426\type{ConcreteElementA} and \type{ConcreteElementB}. Then each visitor must have
2427the (possibly empty) methods \method{visit(ConcreteElementA element)} and
2428\method{visit(ConcreteElementB element)}. This scenario is depicted in
2429\myref{fig:visitorPattern}.
50976f51 2430
3572a8ac
EK
2431\begin{figure}[h]
2432 \centering
2433 \tikzstyle{abstract}=[rectangle, draw=black, fill=white, drop shadow, text
2434 centered, anchor=north, text=black, text width=6cm, every one node
2435part/.style={align=center, font=\bfseries\itshape}]
2436 \tikzstyle{concrete}=[rectangle, draw=black, fill=white, drop shadow, text
2437 centered, anchor=north, text=black, text width=6cm]
2438 \tikzstyle{inheritarrow}=[->, >=open triangle 90, thick]
2439 \tikzstyle{commentarrow}=[->, >=angle 90, dashed]
2440 \tikzstyle{line}=[-, thick]
2441 \tikzset{every one node part/.style={align=center, font=\bfseries}}
2442 \tikzset{every second node part/.style={align=center, font=\ttfamily}}
3572a8ac
EK
2443
2444 \begin{tikzpicture}[node distance=1cm, scale=0.8, every node/.style={transform
2445 shape}]
2446 \node (Element) [abstract, rectangle split, rectangle split parts=2]
2447 {
2448 \nodepart{one}{Element}
2449 \nodepart{second}{+accept(visitor: Visitor)}
2450 };
2451 \node (AuxNode01) [text width=0, minimum height=2cm, below=of Element] {};
2452 \node (ConcreteElementA) [concrete, rectangle split, rectangle split
2453 parts=2, left=of AuxNode01]
2454 {
2455 \nodepart{one}{ConcreteElementA}
2456 \nodepart{second}{+accept(visitor: Visitor)}
2457 };
2458 \node (ConcreteElementB) [concrete, rectangle split, rectangle split
2459 parts=2, right=of AuxNode01]
2460 {
2461 \nodepart{one}{ConcreteElementB}
2462 \nodepart{second}{+accept(visitor: Visitor)}
2463 };
2464
2465 \node[comment, below=of ConcreteElementA] (CommentA) {visitor.visit(this)};
2466
2467 \node[comment, below=of ConcreteElementB] (CommentB) {visitor.visit(this)};
2468
2469 \node (AuxNodeX) [text width=0, minimum height=1cm, below=of AuxNode01] {};
2470
2471 \node (Visitor) [abstract, rectangle split, rectangle split parts=2,
2472 below=of AuxNodeX]
2473 {
2474 \nodepart{one}{Visitor}
2475 \nodepart{second}{+visit(ConcreteElementA)\\+visit(ConcreteElementB)}
2476 };
2477 \node (AuxNode02) [text width=0, minimum height=2cm, below=of Visitor] {};
2478 \node (ConcreteVisitor1) [concrete, rectangle split, rectangle split
2479 parts=2, left=of AuxNode02]
2480 {
2481 \nodepart{one}{ConcreteVisitor1}
2482 \nodepart{second}{+visit(ConcreteElementA)\\+visit(ConcreteElementB)}
2483 };
2484 \node (ConcreteVisitor2) [concrete, rectangle split, rectangle split
2485 parts=2, right=of AuxNode02]
2486 {
2487 \nodepart{one}{ConcreteVisitor2}
2488 \nodepart{second}{+visit(ConcreteElementA)\\+visit(ConcreteElementB)}
2489 };
2490
2491
2492 \draw[inheritarrow] (ConcreteElementA.north) -- ++(0,0.7) -|
2493 (Element.south);
2494 \draw[line] (ConcreteElementA.north) -- ++(0,0.7) -|
2495 (ConcreteElementB.north);
2496
2497 \draw[inheritarrow] (ConcreteVisitor1.north) -- ++(0,0.7) -|
2498 (Visitor.south);
2499 \draw[line] (ConcreteVisitor1.north) -- ++(0,0.7) -|
2500 (ConcreteVisitor2.north);
2501
2502 \draw[commentarrow] (CommentA.north) -- (ConcreteElementA.south);
2503 \draw[commentarrow] (CommentB.north) -- (ConcreteElementB.south);
2504
2505
2506 \end{tikzpicture}
2507 \caption{The Visitor Pattern.}
2508 \label{fig:visitorPattern}
2509\end{figure}
2510
0a8ca90c
EK
2511The use of the visitor pattern can be appropriate when the hierarchy of elements
2512is mostly stable, but the family of operations over its elements is constantly
fe0a4c48 2513growing. This is clearly the case for the \name{Eclipse} AST, since the hierarchy of
0a8ca90c
EK
2514type \type{ASTNode} is very stable, but the functionality of its elements is
2515extended every time someone needs to operate on the AST. Another aspect of the
fe0a4c48 2516\name{Eclipse} implementation is that it is a public API, and the visitor pattern is an
0a8ca90c
EK
2517easy way to provide access to the nodes in the tree.
2518
fe0a4c48 2519The version of the visitor pattern implemented for the AST nodes in \name{Eclipse} also
0a8ca90c
EK
2520provides an elegant way to traverse the tree. It does so by following the
2521convention that every node in the tree first let the visitor visit itself,
b3adff95
EK
2522before it also makes all its children accept the visitor. The children are only
2523visited if the visit method of their parent returns \var{true}. This pattern
2524then makes for a prefix traversal of the AST. If postfix traversal is desired,
2525the visitors also has \method{endVisit} methods for each node type, that is
2526called after the \method{visit} method for a node. In addition to these visit
2527methods, there are also the methods \method{preVisit(ASTNode)},
2528\method{postVisit(ASTNode)} and \method{preVisit2(ASTNode)}. The
2529\method{preVisit} method is called before the type-specific \method{visit}
2530method. The \method{postVisit} method is called after the type-specific
2531\method{endVisit}. The type specific \method{visit} is only called if
2532\method{preVisit2} returns \var{true}. Overriding the \method{preVisit2} is also
2533altering the behavior of \method{preVisit}, since the default implementation is
94c59647
EK
2534responsible for calling it.
2535
2536An example of a trivial \type{ASTVisitor} is shown in
2537\myref{lst:astVisitorExample}.
2538
2539\begin{listing}
2540\begin{minted}{java}
2541public class CollectNamesVisitor extends ASTVisitor {
2542 Collection<Name> names = new LinkedList<Name>();
2543
2544 @Override
2545 public boolean visit(QualifiedName node) {
2546 names.add(node);
2547 return false;
2548 }
2549
2550 @Override
2551 public boolean visit(SimpleName node) {
2552 names.add(node);
2553 return true;
2554 }
2555}
2556\end{minted}
2557\caption{An \type{ASTVisitor} that visits all the names in a subtree and adds
2558them to a collection, except those names that are children of any
2559\type{QualifiedName}.}
2560\label{lst:astVisitorExample}
2561\end{listing}
2562
b8fce5af
EK
2563\section{Property collectors}\label{propertyCollectors}
2564The prefixes and unfixes are found by property
2565collectors\typeref{no.uio.ifi.refaktor.extractors.collectors.PropertyCollector}.
2566A property collector is of the \type{ASTVisitor} type, and thus visits nodes of
2567type \type{ASTNode} of the abstract syntax tree \see{astVisitor}.
2568
2569\subsection{The PrefixesCollector}
2570The \typewithref{no.uio.ifi.refaktor.extractors.collectors}{PrefixesCollector}
ccd252c5 2571finds prefixes that makes up the basis for calculating move targets for the
fe0a4c48 2572\refa{Extract and Move Method} refactoring. It visits expression
b8fce5af
EK
2573statements\typeref{org.eclipse.jdt.core.dom.ExpressionStatement} and creates
2574prefixes from its expressions in the case of method invocations. The prefixes
2575found is registered with a prefix set, together with all its sub-prefixes.
2576
2577\subsection{The UnfixesCollector}\label{unfixes}
2578The \typewithref{no.uio.ifi.refaktor.extractors.collectors}{UnfixesCollector}
2579finds unfixes within a selection. That is prefixes that cannot be used as a
2580basis for finding a move target in a refactoring.
2581
2582An unfix can be a name that is assigned to within a selection. The reason that
2583this cannot be allowed, is that the result would be an assignment to the
2584\type{this} keyword, which is not valid in Java \see{eclipse_bug_420726}.
2585
2586Prefixes that originates from variable declarations within the same selection
2587are also considered unfixes. This is because when a method is moved, it needs to
2588be called through a variable. If this variable is also within the method that is
2589to be moved, this obviously cannot be done.
2590
2591Also considered as unfixes are variable references that are of types that is not
2592suitable for moving a methods to. This can be either because it is not
2593physically possible to move the method to the desired class or that it will
2594cause compilation errors by doing so.
2595
2596If the type binding for a name is not resolved it is considered and unfix. The
2597same applies to types that is only found in compiled code, so they have no
2598underlying source that is accessible to us. (E.g. the \type{java.lang.String}
2599class.)
2600
2601Interfaces types are not suitable as targets. This is simply because interfaces
3ab3e132 2602in Java cannot contain methods with bodies. (This thesis does not deal with
b8fce5af
EK
2603features of Java versions later than Java 7. Java 8 has interfaces with default
2604implementations of methods.) Neither are local types allowed. This accounts for
2605both local and anonymous classes. Anonymous classes are effectively the same as
2606interface types with respect to unfixes. Local classes could in theory be used
2607as targets, but this is not possible due to limitations of the implementation of
fe0a4c48 2608the \refa{Extract and Move Method} refactoring. The problem is that the refactoring is
b8fce5af
EK
2609done in two steps, so the intermediate state between the two refactorings would
2610not be legal Java code. In the case of local classes, the problem is that, in
2611the intermediate step, a selection referencing a local class would need to take
2612the local class as a parameter if it were to be extracted to a new method. This
2613new method would need to live in the scope of the declaring class of the
2614originating method. The local class would then not be in the scope of the
2615extracted method, thus bringing the source code into an illegal state. One could
2616imagine that the method was extracted and moved in one operation, without an
2617intermediate state. Then it would make sense to include variables with types of
2618local classes in the set of legal targets, since the local classes would then be
2619in the scopes of the method calls. If this makes any difference for software
2620metrics that measure coupling would be a different discussion.
2621
2622\begin{listing}
2623\begin{multicols}{2}
2624\begin{minted}[]{java}
2625// Before
2626void declaresLocalClass() {
2627 class LocalClass {
2628 void foo() {}
2629 void bar() {}
2630 }
2631
2632 LocalClass inst =
2633 new LocalClass();
2634 inst.foo();
2635 inst.bar();
2636}
2637\end{minted}
2638
2639\columnbreak
2640
2641\begin{minted}[]{java}
2642// After Extract Method
2643void declaresLocalClass() {
2644 class LocalClass {
2645 void foo() {}
2646 void bar() {}
2647 }
2648
2649 LocalClass inst =
2650 new LocalClass();
2651 fooBar(inst);
2652}
2653
2654// Intermediate step
2655void fooBar(LocalClass inst) {
2656 inst.foo();
2657 inst.bar();
2658}
2659\end{minted}
2660\end{multicols}
fe0a4c48 2661\caption{When \refa{Extract and Move Method} tries to use a variable with a local type
b8fce5af
EK
2662as the move target, an intermediate step is taken that is not allowed. Here:
2663\type{LocalClass} is not in the scope of \method{fooBar} in its intermediate
2664location.}
2665\label{lst:extractMethod_LocalClass}
2666\end{listing}
2667
2668The last class of names that are considered unfixes is names used in null tests.
2669These are tests that reads like this: if \texttt{<name>} equals \var{null} then
2670do something. If allowing variables used in those kinds of expressions as
2671targets for moving methods, we would end up with code containing boolean
2672expressions like \texttt{this == null}, which would not be meaningful, since
2673\var{this} would never be \var{null}.
2674
0a8ca90c 2675
5195bf0c
EK
2676\subsection{The ContainsReturnStatementCollector}
2677The
2678\typewithref{no.uio.ifi.refaktor.analyze.collectors}{ContainsReturnStatementCollector}
2679is a very simple property collector. It only visits the return statements within
2680a selection, and can report whether it encountered a return statement or not.
2681
b8d069e4
EK
2682\subsection{The LastStatementCollector}
2683The \typewithref{no.uio.ifi.refaktor.analyze.collectors}{LastStatementCollector}
2684collects the last statement of a selection. It does so by only visiting the top
2685level statements of the selection, and compares the textual end offset of each
3ab3e132 2686encountered statement with the end offset of the previous statement found.
b8d069e4 2687
95c0f364 2688\section{Checkers}\label{checkers}
801ff00a 2689\todoin{Check out ExtractMethodAnalyzer from ExtractMethodRefactoring}
d6f8e65a
EK
2690The checkers are a range of classes that checks that text selections complies
2691with certain criteria. All checkers operates under the assumption that the code
2692they check is free from compilation errors. If a
95c0f364
EK
2693\typewithref{no.uio.ifi.refaktor.analyze.analyzers}{Checker} fails, it throws a
2694\type{CheckerException}. The checkers are managed by the
2695\type{LegalStatementsChecker}, which does not, in fact, implement the
2696\type{Checker} interface. It does, however, run all the checkers registered with
2697it, and reports that all statements are considered legal if no
08cbba3b 2698\type{CheckerException} is thrown. Many of the checkers either extends the
f72f72f1 2699\type{PropertyCollector} or utilizes one or more property collectors to verify
3ab3e132 2700some criteria. The checkers registered with the \type{LegalStatementsChecker}
f72f72f1 2701are described next. They are run in the order presented below.
95c0f364 2702
a22915d0
EK
2703\subsection{The CallToProtectedOrPackagePrivateMethodChecker}
2704This checker is designed to prevent an error that can occur in situations where
2705a method is declared in one class, but overridden in another. If a text
2706selection contains a call to a method like this, and the seletion is extracted
2707to a new method, the subsequent movement of this method could cause the code to
2708break.
2709
2710The code breaks in situations where the method call in the selection is to a
2711method that has the \code{protected} modifier, or it does not have any access
2712modifiers, i.e. it is package-private. The method is not public, so the
2713\MoveMethod refactoring must make it public, making the moved method able to
2714call it from its new location. The problem is that the, now public, method is
2715overridden in a subclass, where it has a protected or package-private status.
2716This makes the compiler complain that the subclass is trying to reduce the
2717visibility of a method declared in its superclass. This is not allowed in Java,
2718and for good reasons. It would make it possible to make a subclass that could
2719not be a substitute for its superclass.
2720
2721The workings of the \type{CallToProtectedOrPackagePrivateMethod\-Checker} is
2722therefore very simple. It looks for calls to methods that are either protected
2723or package-private within the selection, and throws an
2724\type{IllegalExpressionFoundException} if one is found.
2725
2726The problem this checker helps to avoid, is a little subtle. The problem does
2727not arise in the class where the change is done, but in a class derived from it.
2728This shows that classes acting as superclasses are especially fragile to
2729introducing errors in the context of automated refactoring. This is also shown
2730in bug\ldots \todoin{File Eclipse bug report}
2731
2a4b8dea
EK
2732\subsection{The InstantiationOfNonStaticInnerClassChecker}
2733When a non-static inner class is instatiated, this must happen in the scope of
2734its declaring class. This is because it must have access to the members of the
2735declaring class. If the inner class is public, it is possible to instantiate it
2736through an instance of its declaring class, but this is not handled by the
2737\type{MoveInstanceMethodProcessor} in Eclipse when moving a method. Therefore,
2738performing a move on a method that instantiates a non-static inner class, will
2739break the code if the instantiation is not handled properly. For this reason,
2740the \type{InstantiationOfNonStaticInnerClassChecker} does not validate
2741selections that contains instantiations of non-static inner classes. This
2742problem is also related to bug\ldots \todoin{File Eclipse bug report}
2743
8d0caf4c
EK
2744\subsection{The EnclosingInstanceReferenceChecker}
2745The purpose of this checker is to verify that the names in a selection is not
2746referencing any enclosing instances. This is for making sure that all references
2747is legal in a method that is to be moved. Theoretically, some situations could
2748be easily solved my passing a reference to the referenced class with the moved
2749method (e.g. when calling public methods), but the dependency on the
2750\type{MoveInstanceMethodProcessor} prevents this.
2751
2752The
2753\typewithref{no.uio.ifi.refaktor.analyze.analyzers}{EnclosingInstanceReferenceChecker}
2754is a modified version of the
801ff00a 2755\typewithref{org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethod\-Processor}{EnclosingInstanceReferenceFinder}
8d0caf4c
EK
2756from the \type{MoveInstanceMethodProcessor}. Wherever the
2757\type{EnclosingInstanceReferenceFinder} would create a fatal error status, the
2758checker throws a \type{CheckerException}.
2759
2760It works by first finding all of the enclosing types of a selection. Thereafter
2761it visits all its simple names to check that they are not references to
2762variables or methods declared in any of the enclosing types. In addition the
2763checker visits \var{this}-expressions to verify that no such expressions is
2764qualified with any name.
2765
9cc2cd59 2766\subsection{The ReturnStatementsChecker}\label{returnStatementsChecker}
801ff00a 2767The checker for return statements is meant to verify that if a text selection
d6f8e65a
EK
2768contains a return statement, then every possible execution path within the
2769selection ends in a return statement. This property is important regarding the
2770\ExtractMethod refactoring. If it holds, it means that a method could be
2771extracted from the selection, and a call to it could be substituted for the
801ff00a
EK
2772selection. If the method has a non-void return type, then a call to it would
2773also be a valid return point for the calling method. If its return value is of
2774the void type, then the \type{ExtractMethodRefactoring} of \name{Eclipse}
2775appends an empty return statement to the back of the method call. Therefore, the
2776analysis does not discriminate on either kinds of return statements, with or
2777without a return value.
2778
2779The property description implies that if the selection is free from return
d6f8e65a
EK
2780statements, then the checker validates. So this is the first thing the checker
2781investigates.
2782
2783If the checker proceedes any further, it is because the selection contains one
2784or more return statements. The next test is therefore to check if the last
801ff00a
EK
2785statement of the selection ends in either a return or a throw statement. If the
2786last statement of the selection ends in a return statement, then all execution
d6f8e65a
EK
2787paths within the selection should end in either this, or another, return
2788statement. This is also true for a throw statement, since it causes an immediate
2789exit from the current block, together with all outer blocks in its control flow
2790that does not catch the thrown exception.
2791
2792Return statements can be either explicit or implicit. An \emph{explicit} return
2793statement is formed by using the \code{return} keyword, while an \emph{implicit}
2794return statement is a statement that is not formed by the \code{return} keyword,
801ff00a
EK
2795but must be the last statement of a method that can have any side effects. This
2796can happen in methods with a void return type. An example is a statement that is
2797inside one or more blocks. The last statement of a method could for instance be
2798an if-statement, but the last statement that is executed in the method, and that
2799can have any side effects, may be located inside the block of the else part of
2800the if-statement.
2801
2802The responsibility for checking that the last statement of the selection
2803eventually ends in a return or throw statement, is put on the
2804\type{LastStatementOfSelectionEndsInReturnOrThrowChecker}. For every node
2805visited, if it is a statement, it does a test to see if the statement is a
2806return, a throw or if it is an implicit return statement. If this is the case,
2807no further checking is done. This checking is done in the \code{preVisit2}
2808method \see{astVisitor}. If the node is not of a type that is being handled by
2809its type specific visit method, the checker performs a simple test. If the node
2810being visited is not the last statement of its parent that is also enclosed by
2811the selection, an \type{IllegalStatementFoundException} is thrown. This ensures
2812that all statements are taken care of, one way or the other. It also ensures
2813that the checker is conservative in the way it checks for legality of the
2814selection.
2815
2816To examine if a statement is an implicit return statement, the checker first
2817finds the last statement declared in its enclosing method. If this statement is
2818the same as the one under investigation, it is considered an implicit return
2819statement. If the statements are not the same, the checker does a search to see
2820if statement examined is also the last statement of the method that can be
2821reached. This includes the last statement of a block statement, a labeled
2822statement, a synchronized statement or a try statement, that in turn is the last
2823statement enclosed by the statement types listed. This search goes through all
2824the parents of a statement until a statement is found that is not one of the
2825mentioned acceptable parent statements. If the search ends in a method
2826declaration, then the statement is considered to be the last reachable statement
2827of the method, and thus also an implicit return statement.
2828
2829There are two kinds of statements that are handled explicitly. It is
2830if-statements and try-statements. Block, labeled and do-statements are handled
2831by fall-through to the other two. Do-statements are considered equal to blocks
2832in this context, since their bodies are always evaluated at least one time. If-
2833and try-statements are visited only if they are the last node of their parent
2834within the selection.
2835
2836For if-statements, the rule is that if the then-part does not contain any return
2837or throw statements, it is considered illegal. If it does contain a return or
2838throw, its else-part is checked. If the else-part is non-existent, or it does
2839not contain any return or throw statements, it is considered illegal. If the
2840statement is not regarded illegal, its children are visited.
2841
2842Try-statements are handled much the same way as if-statements. Its body must
2843contain a return or throw. The same applies to its catch clauses and finally
2844body.
2845
2846If the checker does not complain at any point, the selection is considered valid
2847with respect to return statements.
41cde50e
EK
2848
2849\subsection{The AmbiguousReturnValueChecker}
9cc2cd59
EK
2850This checker verifies that there are no \emph{ambiguous return statements} in a
2851selection. The problem with ambiguous return statements arise when a selection
2852is chosen to be extracted into a new method, but it needs to return more than
2853one value from that method. This problem occurs in two situations. The first
2854situation arise when there is more than one local variable that is both assigned
2855to within a selection and also referenced after the selection. The other
2856situation occur when there is only one such assignment, but there is also one or
2857more return statements in the selection.
2858
2859First the checker needs to collect some data. Those data are the binding keys
2860for all simple names that are assigned to within the selection, including
2861variable declarations, but excluding fields. The checker also collects whether
2862there exists a return statement in the selection or not. No further checks of
2863return statements are needed, since, at this point, the selection is already
2864checked for illegal return statements \see{returnStatementsChecker}.
2865
2866After the binding keys of the assignees are collected, the checker searches the
2867part of the enclosing method that is after the selection for references whose
3ab3e132
EK
2868binding keys are among the collected keys. If more than one unique referral is
2869found, or only one referral is found, but the selection also contains a return
2870statement, we have a situation with an ambiguous return value, and an exception
2871is thrown.
9cc2cd59
EK
2872
2873%\todoin{Explain why we do not need to consider variables assigned inside
2874%local/anonymous classes. (The referenced variables need to be final and so
2875%on\ldots)}
41cde50e
EK
2876
2877\subsection{The IllegalStatementsChecker}
2878This checker is designed to check for illegal statements.
2879
08cbba3b
EK
2880Any use of the \var{super} keyword is prohibited, since its meaning is altered
2881when moving a method to another class.
2882
2883For a \emph{break} statement, there is two situations to consider: A break
2884statement with or without a label. If the break statement has a label, it is
2885checked that whole of the labeled statement is inside the selection. Since a
2886label does not have any binding information, we have to search upwards in the
2887AST to find the \type{LabeledStatement} that corresponds to the label from the
2888break statement, and check that it is contained in the selection. If the break
2889statement does not have a label attached to it, it is checked that its innermost
2890enclosing loop or switch statement also is inside the selection.
2891
2892The situation for a \emph{continue} statement is the same as for a break
2893statement, except that it is not allowed inside switch statements.
2894
2895Regarding \emph{assignments}, two types of assignments is allowed: Assignment to
2896a non-final variable and assignment to an array access. All other assignments is
2897regarded illegal.
2898
2899\todoin{Finish\ldots}
41cde50e 2900
356782a0
EK
2901
2902\chapter{Benchmarking}
2903\todoin{Better name than ``benchmarking''?}
fe0a4c48 2904This part of the master project is located in the \name{Eclipse} project
356782a0
EK
2905\code{no.uio.ifi.refaktor.benchmark}. The purpose of it is to run the equivalent
2906of the \type{SearchBasedExtractAndMoveMethodChanger}
2907\see{searchBasedExtractAndMoveMethodChanger} over a larger software project,
3ab3e132 2908both to test its robustness but also its effect on different software metrics.
356782a0
EK
2909
2910\section{The benchmark setup}
fe0a4c48
EK
2911The benchmark itself is set up as a \name{JUnit} test case. This is a convenient
2912setup, and utilizes the \name{JUnit Plugin Test Launcher}. This provides us a
2913with a fully functional \name{Eclipse} workbench. Most importantly, this gives
2914us access to the Java Model of \name{Eclipse} \see{javaModel}.
356782a0
EK
2915
2916\subsection{The ProjectImporter}
2917The Java project that is going to be used as the data for the benchmark, must be
2918imported into the JUnit workspace. This is done by the
2919\typewithref{no.uio.ifi.refaktor.benchmark}{ProjectImporter}. The importer
2920require the absolute path to the project description file. It is named
2921\code{.project} and is located at the root of the project directory.
2922
2923The project description is loaded to find the name of the project to be
2924imported. The project that shall be the destination for the import is created in
2925the workspace, on the base of the name from the description. Then an import
2926operation is created, based on both the source and destination information. The
2927import operation is run to perform the import.
2928
2929I have found no simple API call to accomplish what the importer does, which
fe0a4c48
EK
2930tells me that it may not be too many people performing this particular action.
2931The solution to the problem was found on \name{Stack
356782a0 2932Overflow}\footnote{\url{https://stackoverflow.com/questions/12401297}}. It
3ab3e132 2933contains enough dirty details to be considered inconvenient to use, if not
356782a0
EK
2934wrapping it in a class like my \type{ProjectImporter}. One would probably have
2935to delve into the source code for the import wizard to find out how the import
2936operation works, if no one had already done it.
2937
8fe94c0b
EK
2938\section{Statistics}
2939Statistics for the analysis and changes is captured by the
2940\typewithref{no.uio.ifi.refaktor.aspects}{StatisticsAspect}. This an
fe0a4c48 2941\emph{aspect} written in \name{AspectJ}.
8fe94c0b
EK
2942
2943\subsection{AspectJ}
fe0a4c48 2944\name{AspectJ}\footnote{\url{http://eclipse.org/aspectj/}} is an extension to
8fe94c0b
EK
2945the Java language, and facilitates combining aspect-oriented programming with
2946the object-oriented programming in Java.
2947
2948Aspect-oriented programming is a programming paradigm that is meant to isolate
2949so-called \emph{cross-cutting concerns} into their own modules. These
dd73ba39
EK
2950cross-cutting concerns are functionalities that spans over multiple classes, but
2951may not belong naturally in any of them. It can be functionality that does not
2952concern the business logic of an application, and thus may be a burden when
2953entangled with parts of the source code it does not really belong. Examples
2954include logging, debugging, optimization and security.
8fe94c0b 2955
416b6888
EK
2956Aspects are interacting with other modules by defining advices. The concept of
2957an \emph{advice} is known from both aspect-oriented and functional
2958programming\citing{wikiAdvice2014}. It is a function that modifies another
2959function when the latter is run. An advice in AspectJ is somewhat similar to a
2960method in Java. It is meant to alter the behavior of other methods, and contains
2961a body that is executed when it is applied.
8fe94c0b
EK
2962
2963An advice can be applied at a defined \emph{pointcut}. A pointcut picks out one
2964or more \emph{join points}. A join point is a well-defined point in the
2965execution of a program. It can occur when calling a method defined for a
2966particular class, when calling all methods with the same name,
2967accessing/assigning to a particular field of a given class and so on. An advice
dd73ba39
EK
2968can be declared to run both before, after returning from a pointcut, when there
2969is thrown an exception in the pointcut or after the pointcut either returns or
2970throws an exception. In addition to picking out join points, a pointcut can
2971also bind variables from its context, so they can be accessed in the body of an
2972advice. An example of a pointcut and an advice is found in
2973\myref{lst:aspectjExample}.
8fe94c0b
EK
2974
2975\begin{listing}[h]
c8088eec 2976\begin{minted}{aspectj}
8fe94c0b
EK
2977pointcut methodAnalyze(
2978 SearchBasedExtractAndMoveMethodAnalyzer analyzer) :
2979 call(* SearchBasedExtractAndMoveMethodAnalyzer.analyze())
2980 && target(analyzer);
2981
2982after(SearchBasedExtractAndMoveMethodAnalyzer analyzer) :
2983 methodAnalyze(analyzer) {
2984 statistics.methodCount++;
2985 debugPrintMethodAnalysisProgress(analyzer.method);
2986}
2987\end{minted}
2988\caption{An example of a pointcut named \method{methodAnalyze},
2989and an advice defined to be applied after it has occurred.}
2990\label{lst:aspectjExample}
2991\end{listing}
2992
dd73ba39
EK
2993\subsection{The Statistics class}
2994The statistics aspect stores statistical information in an object of type
2995\type{Statistics}. As of now, the aspect needs to be initialized at the point in
2996time where it is desired that it starts its data gathering. At any point in time
2997the statistics aspect can be queried for a snapshot of the current statistics.
2998
2999The \type{Statistics} class also include functionality for generating a report
3000of its gathered statistics. The report can be given either as a string or it can
3001be written to a file.
3002
3003\subsection{Advices}
3004The statistics aspect contains advices for gathering statistical data from
3005different parts of the benchmarking process. It captures statistics from both
3006the analysis part and the execution part of the composite \ExtractAndMoveMethod
3007refactoring.
3008
3009For the analysis part, there are advices to count the number of text selections
3010analyzed and the number of methods, types, compilation units and packages
3011analyzed. There are also advices that counts for how many of the methods there
3012is found a selection that is a candidate for the refactoring, and for how many
3ab3e132 3013methods there is not.
dd73ba39
EK
3014
3015There exists advices for counting both the successful and unsuccessful
3016executions of all the refactorings. Both for the \ExtractMethod and \MoveMethod
3017refactorings in isolation, as well as for the combination of them.
3018
8fe94c0b 3019\section{Optimizations}
41293210 3020When looking for optimizations to make for the benchmarking process, I used the
fe0a4c48 3021\name{VisualVM}\footnote{\url{http://visualvm.java.net/}} for the Java Virtual
41293210
EK
3022Machine to both profile the application and also to make memory dumps of its
3023heap.
8fe94c0b
EK
3024
3025\subsection{Caching}
41293210
EK
3026When profiling the benchmark process before making any optimizations, it early
3027became apparent that the parsing of source code was a place to direct attention
3028towards. This discovery was done when only \emph{analyzing} source code, before
3029trying to do any \emph{manipulation} of it. Caching of the parsed ASTs seemed
3030like the best way to save some time, as expected. With only a simple cache of
3031the most recently used AST, the analysis time was speeded up by a factor of
3032around
303320. This number depends a little upon which type of system the analysis was
3034run.
3035
3036The caching is managed by a cache manager, that now, by default, utilizes the
3037not so well known feature of Java called a \emph{soft reference}. Soft
3038references are best explained in the context of weak references. A \emph{weak
3039reference} is a reference to an object instance that is only guaranteed to
3040persist as long as there is a \emph{strong reference} or a soft reference
3041referring the same object. If no such reference is found, its referred object is
3042garbage collected. A strong reference is basically the same as a regular Java
3043reference. A soft reference has the same guarantees as a week reference when it
3044comes to its relation to strong references, but it is not necessarily garbage
3045collected whenever there exists no strong references to it. A soft reference
3046\emph{may} reside in memory as long as the JVM has enough free memory in the
3047heap. A soft reference will therefore usually perform better than a weak
3048reference when used for simple caching and similar tasks. The way to use a
3049soft/weak reference is to as it for its referent. The return value then has to
3050be tested to check that it is not \var{null}. For the basic usage of soft
3051references, see \myref{lst:softReferenceExample}. For a more thorough
3052explanation of weak references in general, see\citing{weakRef2006}.
3053
3054\begin{listing}[h]
3055\begin{minted}{java}
3056// Strong reference
3057Object strongRef = new Object();
3058
3059// Soft reference
3060SoftReference<Object> softRef =
3061 new SoftReference<Object>(new Object());
3062
3063// Using the soft reference
3064Object obj = softRef.get();
3065if (obj != null) {
3066 // Use object here
3067}
3068\end{minted}
3069\caption{Showing the basic usage of soft references. Weak references is used the
3070 same way. {\footnotesize (The references are part of the \code{java.lang.ref}
3071package.)}}
3072\label{lst:softReferenceExample}
3073\end{listing}
3074
3075The cache based on soft references has no limit for how many ASTs it caches. It
3076is generally not advisable to keep references to ASTs for prolonged periods of
3077time, since they are expensive structures to hold on to. For regular plugin
fe0a4c48 3078development, \name{Eclipse} recommends not creating more than one AST at a time to
41293210
EK
3079limit memory consumption. Since the benchmarking has nothing to do with user
3080experience, and throughput is everything, these advices are intentionally
fe0a4c48 3081ignored. This means that during the benchmarking process, the target \name{Eclipse}
41293210
EK
3082application may very well work close to its memory limit for the heap space for
3083long periods during the benchmark.
8fe94c0b
EK
3084
3085\subsection{Memento}
d6f8e65a 3086\todoin{Write}
356782a0 3087
a7514fbd
EK
3088
3089\chapter{Technicalities}
3090
3091\section{Source code organization}
3092All the parts of this master project is under version control with
3093\name{Git}\footnote{\url{http://git-scm.com/}}.
3094
3095The software written is organized as some \name{Eclipse} plugins. Writing a plugin is
3096the natural way to utilize the API of \name{Eclipse}. This also makes it possible to
3097provide a user interface to manually run operations on selections in program
3098source code or whole projects/packages.
3099
3100When writing a plugin in \name{Eclipse}, one has access to resources such as the
3101current workspace, the open editor and the current selection.
3102
3103The thesis work is contained in the following Eclipse projects:
3104
3105\begin{description}
3106 \item[no.uio.ifi.refaktor] \hfill \\ This is the main Eclipse plugin
3107 project, and contains all of the business logic for the plugin.
3108
3109 \item[no.uio.ifi.refaktor.tests] \hfill \\
3110 This project contains the tests for the main plugin.
3111
3112 \item[no.uio.ifi.refaktor.examples] \hfill \\
3113 Contains example code used in testing. It also contains code for managing
3114 this example code, such as creating an Eclipse project from it before a test
3115 run.
3116
3117 \item[no.uio.ifi.refaktor.benchmark] \hfill \\
3118 This project contains code for running search based versions of the
3119 composite refactoring over selected Eclipse projects.
3120
3121 \item[no.uio.ifi.refaktor.releng] \hfill \\
3122 Contains the rmap, queries and target definitions needed by by Buckminster
3123 on the Jenkins continuous integration server.
3124
3125\end{description}
3126
3127\subsection{The no.uio.ifi.refaktor project}
3128
3129\subsubsection{no.uio.ifi.refaktor.analyze}
3130This package, and its subpackages, contains code that is used for analyzing Java
3131source code. The most important subpackages are presented below.
3132
3133\begin{description}
3134 \item[no.uio.ifi.refaktor.analyze.analyzers] \hfill \\
3135 This package contains source code analyzers. These are usually responsible
3136 for analyzing text selections or running specialized analyzers for different
3137 kinds of entities. Their structure are often hierarchical. This means that
3138 you have an analyzer for text selections, that in turn is utilized by an
3139 analyzer that analyzes all the selections of a method. Then there are
3140 analyzers for analyzing all the methods of a type, all the types of a
3141 compilation unit, all the compilation units of a package, and, at last, all
3142 of the packages in a project.
3143
3144 \item[no.uio.ifi.refaktor.analyze.checkers] \hfill \\
3145 A package containing checkers. The checkers are classes used to validate
3146 that a selection can be further analyzed and chosen as a candidate for a
3147 refactoring. Invalidating properties can be such as usage of inner classes
3148 or the need for multiple return values.
3149
3150 \item[no.uio.ifi.refaktor.analyze.collectors] \hfill \\
3151 This package contains the property collectors. Collectors are used to gather
3152 properties from a text selection. This is mostly properties regarding
3153 referenced names and their occurrences. It is these properties that makes up
3154 the basis for finding the best candidates for a refactoring.
3155\end{description}
3156
3157\subsubsection{no.uio.ifi.refaktor.change}
3158This package, and its subpackages, contains functionality for manipulate source
3159code.
3160
3161\begin{description}
3162 \item[no.uio.ifi.refaktor.change.changers] \hfill \\
3163 This package contains source code changers. They are used to glue together
3164 the analysis of source code and the actual execution of the changes.
3165
3166 \item[no.uio.ifi.refaktor.change.executors] \hfill \\
3167 The executors that are responsible for making concrete changes are found in
3168 this package. They are mostly used to create and execute one or more Eclipse
3169 refactorings.
3170
3171 \item[no.uio.ifi.refaktor.change.processors] \hfill \\
3172 Contains a refactoring processor for the \MoveMethod refactoring. The code
3173 is stolen and modified to fix a bug. The related bug is described in
3174 \myref{eclipse_bug_429416}.
3175
3176\end{description}
3177
3178\subsubsection{no.uio.ifi.refaktor.handlers}
3179This package contains handlers for the commands defined in the plugin manifest.
3180
3181\subsubsection{no.uio.ifi.refaktor.prefix}
3182This package contains the \type{Prefix} type that is the data representation of
3183the prefixes found by the \type{PrefixesCollector}. It also contains the prefix
3184set for storing and working with prefixes.
3185
3186\subsubsection{no.uio.ifi.refaktor.statistics}
3187The package contains statistics functionality. Its heart is the statistics
3188aspect that is responsible for gathering statistics during the execution of the
3189\ExtractAndMoveMethod refactoring.
3190
3191\begin{description}
3192 \item[no.uio.ifi.refaktor.statistics.reports] \hfill \\
3193 This package contains a simple framework for generating reports from the
3194 statistics data generated by the aspect. Currently, the only available
3195 report type is a simple text report.
3196
3197\end{description}
3198
3199
3200\subsubsection{no.uio.ifi.refaktor.textselection}
3201This package contains the two custom text selections that are used extensively
3202throughout the project. One of them is just a subclass of the other, to support
3203the use of the memento pattern to optimize the memory usage during benchmarking.
3204
3205\subsubsection{no.uio.ifi.refaktor.debugging}
3206The package contains a debug utility class. I addition to this, the package
3207\code{no.uio.ifi.refaktor.utils.aspects} contains a couple of aspects used for
3208debugging purposes.
3209
3210\subsubsection{no.uio.ifi.refaktor.utils}
3211Utility package that contains all the functionality that has to do with parsing
3212of source code. It also has utility classes for looking up handles to methods
3213and types et cetera.
3214
3215\begin{description}
3216 \item[no.uio.ifi.refaktor.utils.caching] \hfill \\
3217 This package contains the caching manager for compilation units, along with
3218 classes for different caching strategies.
3219
3220 \item[no.uio.ifi.refaktor.utils.nullobjects] \hfill \\
3221 Contains classes for creating different null objects. Most of the classes is
3222 used to represent null objects of different handle types. These null objects
3223 are returned from various utility classes instead of returning a \var{null}
3224 value when other values are not available.
3225
3226\end{description}
3227
3228\section{Continuous integration}
3229The continuous integration server
3230\name{Jenkins}\footnote{\url{http://jenkins-ci.org/}} has been set up for the
3231project\footnote{A work mostly done by the supervisor.}. It is used as a way to
3232run tests and perform code coverage analysis.
3233
3234To be able to build the \name{Eclipse} plugins and run tests for them with Jenkins, the
3235component assembly project
3236\name{Buckminster}\footnote{\url{http://www.eclipse.org/buckminster/}} is used,
3237through its plugin for Jenkins. Buckminster provides for a way to specify the
3238resources needed for building a project and where and how to find them.
3239Buckminster also handles the setup of a target environment to run the tests in.
3240All this is needed because the code to build depends on an \name{Eclipse}
3241installation with various plugins.
3242
3243\subsection{Problems with AspectJ}
3244The Buckminster build worked fine until introducing AspectJ into the project.
3245When building projects using AspectJ, there are some additional steps that needs
3246to be performed. First of all, the aspects themselves must be compiled. Then the
3247aspects needs to be woven with the classes they affect. This demands a process
3248that does multiple passes over the source code.
3249
3250When using AspectJ with \name{Eclipse}, the specialized compilation and the
3251weaving can be handled by the \name{AspectJ Development
3252Tools}\footnote{\url{https://www.eclipse.org/ajdt/}}. This works all fine, but
3253it complicates things when trying to build a project depending on \name{Eclipse}
3254plugins outside of \name{Eclipse}. There is supposed to be a way to specify a
3255compiler adapter for javac, together with the file extensions for the file types
3256it shall operate. The AspectJ compiler adapter is called
3257\typewithref{org.aspectj.tools.ant.taskdefs}{Ajc11CompilerAdapter}, and it works
3258with files that has the extensions \code{*.java} and \code{*.aj}. I tried to
3259setup this in the build properties file for the project containing the aspects,
3260but to no avail. The project containing the aspects does not seem to be built at
3261all, and the projects that depends on it complains that they cannot find certain
3262classes.
3263
3264I then managed to write an \name{Ant}\footnote{\url{https://ant.apache.org/}}
3265build file that utilizes the AspectJ compiler adapter, for the
3266\code{no.uio.ifi.refaktor} plugin. The problem was then that it could no longer
3267take advantage of the environment set up by Buckminster. The solution to this
3268particular problem was of a ``hacky'' nature. It involves exporting the plugin
3269dependencies for the project to an Ant build file, and copy the exported path
3270into the existing build script. But then the Ant script needs to know where the
3271local \name{Eclipse} installation is located. This is no problem when building
3272on a local machine, but to utilize the setup done by Buckminster is a problem
3273still unsolved. To get the classpath for the build setup correctly, and here
3274comes the most ``hacky'' part of the solution, the Ant script has a target for
3275copying the classpath elements into a directory relative to the project
3276directory and checking it into Git. When no \code{ECLIPSE\_HOME} property is set
3277while running Ant, the script uses the copied plugins instead of the ones
3278provided by the \name{Eclipse} installation when building the project. This
3279obviously creates some problems with maintaining the list of dependencies in the
3280Ant file, as well as remembering to copy the plugins every time the list of
3281dependencies change.
3282
3283The Ant script described above is run by Jenkins before the Buckminster setup
3284and build. When setup like this, the Buckminster build succeeds for the projects
3285not using AspectJ, and the tests are run as normal. This is all good, but it
3286feels a little scary, since the reason for Buckminster not working with AspectJ
3287is still unknown.
3288
3289The problems with building with AspectJ on the Jenkins server lasted for a
3290while, before they were solved. This is reflected in the ``Test Result Trend''
3291and ``Code Coverage Trend'' reported by Jenkins.
3292
3293
e1d6ae87
EK
3294\chapter{Methodology}
3295
3296\section{Evolutionary design}
3297In the programming work for this project, it have tried to use a design strategy
4928aa0b
EK
3298called evolutionary design, also known as continuous or incremental
3299design\citing{wiki_continuous_2014}. It is a software design strategy
3300advocated by the Extreme Programming community. The essence of the strategy is
3301that you should let the design of your program evolve naturally as your
3302requirements change. This is seen in contrast with up-front design, where
3303design decisions are made early in the process.
e1d6ae87
EK
3304
3305The motivation behind evolutionary design is to keep the design of software as
3306simple as possible. This means not introducing unneeded functionality into a
3307program. You should defer introducing flexibility into your software, until it
3308is needed to be able to add functionality in a clean way.
3309
3310Holding up design decisions, implies that the time will eventually come when
3311decisions have to be made. The flexibility of the design then relies on the
3312programmer's abilities to perform the necessary refactoring, and \his confidence
3313in those abilities. From my experience working on this project, I can say that
3314this confidence is greatly enhanced by having automated tests to rely on
3315\see{tdd}.
3316
3317The choice of going for evolutionary design developed naturally. As Fowler
3318points out in his article \tit{Is Design Dead?}, evolutionary design much
3319resembles the ``code and fix'' development strategy\citing{fowler_design_2004}.
3320A strategy that most of us have practiced in school. This was also the case when
3321I first started this work. I had to learn the inner workings of Eclipse and its
3322refactoring-related plugins. That meant a lot of fumbling around with code I did
3323not know, in a trial and error fashion. Eventually I started writing tests for
3324my code, and my design began to evolve.
3325
4928aa0b
EK
3326\section{Test-driven development}\label{tdd}
3327As mentioned before, the project started out as a classic code and fix
3328developmen process. My focus was aimed at getting something to work, rather than
3329doing so according to best practice. This resulted in a project that got out of
3330its starting blocks, but it was not accompanied by any tests. Hence it was soon
3331difficult to make any code changes with the confidence that the program was
3332still correct afterwards (assuming it was so before changing it). I always knew
3333that I had to introduce some tests at one point, but this experience accelerated
3334the process of leading me onto the path of testing.
3335
3336I then wrote tests for the core functionality of the plugin, and thus gained
3337more confidence in the correctness of my code. I could now perform quite drastic
3338changes without ``wetting my pants``. After this, nearly all of the semantic
3339changes done to the business logic of the project, or the addition of new
3340functionality, was made in a test-driven manner. This means that before
3341performing any changes, I would define the desired functionality through a set
3342of tests. I would then run the tests to check that they were run and that they
3343did not pass. Then I would do any code changes necessary to make the tests
3344pass. The definition of how the program is supposed to operate is then captured
3345by the tests. However, this does not prove the correctness of the analysis
3346leading to the test definitions.
3347
3348\section{Continuous integration}
3349\todoin{???}
3350
3351
3727b75b 3352\chapter{Eclipse Bugs Found}
540ca7e4
EK
3353\newcommand{\submittedBugReport}[1]{The submitted bug report can be found on
3354 \url{#1}.}
94bb49f0
EK
3355
3356\section{Eclipse bug 420726: Code is broken when moving a method that is
0f6e45f8
EK
3357assigning to the parameter that is also the move
3358destination}\label{eclipse_bug_420726}
540ca7e4 3359This bug
94bb49f0 3360was found when analyzing what kinds of names that was to be considered as
3727b75b 3361\emph{unfixes} \see{unfixes}.
94bb49f0
EK
3362
3363\subsection{The bug}
3364The bug emerges when trying to move a method from one class to another, and when
3365the target for the move (must be a variable, local or field) is both a parameter
fe0a4c48 3366variable and also is assigned to within the method body. \name{Eclipse} allows this to
94bb49f0
EK
3367happen, although it is the sure path to a compilation error. This is because we
3368would then have an assignment to a \var{this} expression, which is not allowed
540ca7e4
EK
3369in Java.
3370\submittedBugReport{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=420726}
94bb49f0
EK
3371
3372\subsection{The solution}
3373The solution to this problem is to add all simple names that are assigned to in
3374a method body to the set of unfixes.
128adb4f 3375
f1b6174d
EK
3376\section{Eclipse bug 429416: IAE when moving method from anonymous
3377class}\label{eclipse_bug_429416}
540ca7e4 3378I discovered
128adb4f
EK
3379this bug during a batch change on the \type{org.eclipse.jdt.ui} project.
3380
3381\subsection{The bug}
fe0a4c48 3382This bug surfaces when trying to use the \refa{Move Method} refactoring to move a
94bb49f0 3383method from an anonymous class to another class. This happens both for my
fe0a4c48
EK
3384simulation as well as in \name{Eclipse}, through the user interface. It only occurs
3385when \name{Eclipse} analyzes the program and finds it necessary to pass an instance of
94bb49f0 3386the originating class as a parameter to the moved method. I.e. it want to pass a
128adb4f
EK
3387\var{this} expression. The execution ends in an
3388\typewithref{java.lang}{IllegalArgumentException} in
3389\typewithref{org.eclipse.jdt.core.dom}{SimpleName} and its
3390\method{setIdentifier(String)} method. The simple name is attempted created in
3391the method
3392\methodwithref{org.eclipse.jdt.internal.corext.refactoring.structure.\\MoveInstanceMethodProcessor}{createInlinedMethodInvocation}
3393so the \type{MoveInstanceMethodProcessor} was early a clear suspect.
3394
3395The \method{createInlinedMethodInvocation} is the method that creates a method
3396invocation where the previous invocation to the method that was moved was. From
3397its code it can be read that when a \var{this} expression is going to be passed
3398in to the invocation, it shall be qualified with the name of the original
3ab3e132 3399method's declaring class, if the declaring class is either an anonymous class or
128adb4f
EK
3400a member class. The problem with this, is that an anonymous class does not have
3401a name, hence the term \emph{anonymous} class! Therefore, when its name, an
3402empty string, is passed into
3403\methodwithref{org.eclipse.jdt.core.dom.AST}{newSimpleName} it all ends in an
540ca7e4
EK
3404\type{IllegalArgumentException}.
3405\submittedBugReport{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=429416}
128adb4f
EK
3406
3407\subsection{How I solved the problem}
3408Since the \type{MoveInstanceMethodProcessor} is instantiated in the
3409\typewithref{no.uio.ifi.refaktor.change.executors}{MoveMethod\-RefactoringExecutor},
3410and only need to be a
3411\typewithref{org.eclipse.ltk.core.refactoring.participants}{MoveProcessor}, I
3412was able to copy the code for the original move processor and modify it so that
3413it works better for me. It is now called
f1b6174d 3414\typewithref{no.uio.ifi.refaktor.change.processors}{ModifiedMoveInstanceMethodProcessor}.
128adb4f
EK
3415The only modification done (in addition to some imports and suppression of
3416warnings), is in the \method{createInlinedMethodInvocation}. When the declaring
3417class of the method to move is anonymous, the \var{this} expression in the
3418parameter list is not qualified with the declaring class' (empty) name.
3419
3727b75b
EK
3420\section{Eclipse bug 429954: Extracting statement with reference to local type
3421breaks code}\label{eclipse_bug_429954}
540ca7e4 3422The bug
a6415293 3423was discovered when doing some changes to the way unfixes is computed.
3727b75b
EK
3424
3425\subsection{The bug}
fe0a4c48 3426The problem is that \name{Eclipse} is allowing selections that references variables of
3727b75b
EK
3427local types to be extracted. When this happens the code is broken, since the
3428extracted method must take a parameter of a local type that is not in the
3429methods scope. The problem is illustrated in
540ca7e4
EK
3430\myref{lst:extractMethod_LocalClass}, but there in another setting.
3431\submittedBugReport{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=429954}
3727b75b
EK
3432
3433\subsection{Actions taken}
3434There are no actions directly springing out of this bug, since the Extract
a6415293 3435Method refactoring cannot be meant to be this way. This is handled on the
fe0a4c48 3436analysis stage of our \refa{Extract and Move Method} refactoring. So names representing
3727b75b
EK
3437variables of local types is considered unfixes \see{unfixes}.
3438\todoin{write more when fixing this in legal statements checker}
3439
d516ac0b
EK
3440\chapter{Conclusions and Future Work}
3441\todoin{Write}
0e6e57d3 3442
d516ac0b 3443\section{Future work}
0e6e57d3
EK
3444\todoin{Copied from introduction:}
3445For the metrics, I will at least measure the \metr{Coupling between object
3446classes} (CBO) metric that is described by Chidamber and Kemerer in their
3447article \tit{A Metrics Suite for Object Oriented
3448Design}\citing{metricsSuite1994}.
3449
3450\ldots
3451
3452Then the effect of the change must be measured by calculating the chosen
3453software metrics both before and after the execution.
d516ac0b
EK
3454\todoin{Metrics, \ldots}
3455
0d7fbd88
EK
3456\chapter{Related Work}
3457
3458\section{The compositional paradigm of refactoring}
3459This paradigm builds upon the observation of Vakilian et
3460al.\citing{vakilian2012}, that of the many automated refactorings existing in
3461modern IDEs, the simplest ones are dominating the usage statistics. The report
fe0a4c48 3462mainly focuses on \name{Eclipse} as the tool under investigation.
0d7fbd88
EK
3463
3464The paradigm is described almost as the opposite of automated composition of
3465refactorings \see{compositeRefactorings}. It works by providing the programmer
3466with easily accessible primitive refactorings. These refactorings shall be
3467accessed via keyboard shortcuts or quick-assist menus\footnote{Think
fe0a4c48 3468quick-assist with Ctrl+1 in \name{Eclipse}} and be promptly executed, opposed to in the
3ab3e132 3469currently dominating wizard-based refactoring paradigm. They are meant to
0d7fbd88
EK
3470stimulate composing smaller refactorings into more complex changes, rather than
3471doing a large upfront configuration of a wizard-based refactoring, before
3472previewing and executing it. The compositional paradigm of refactoring is
3473supposed to give control back to the programmer, by supporting \himher with an
3474option of performing small rapid changes instead of large changes with a lesser
3475degree of control. The report authors hope this will lead to fewer unsuccessful
3476refactorings. It also could lower the bar for understanding the steps of a
3477larger composite refactoring and thus also help in figuring out what goes wrong
3478if one should choose to op in on a wizard-based refactoring.
3479
3480Vakilian and his associates have performed a survey of the effectiveness of the
3481compositional paradigm versus the wizard-based one. They claim to have found
3482evidence of that the \emph{compositional paradigm} outperforms the
3483\emph{wizard-based}. It does so by reducing automation, which seem
3484counterintuitive. Therefore they ask the question ``What is an appropriate level
3485of automation?'', and thus questions what they feel is a rush toward more
3486automation in the software engineering community.
3487
3488
9ff90080 3489\backmatter{}
fe0a4c48 3490\printglossaries
9ff90080 3491\printbibliography
055dca93 3492\listoftodos
9ff90080 3493\end{document}