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