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