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