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