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