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