1 \documentclass[USenglish]{ifimaster}
3 \usepackage[utf8]{inputenc}
4 \usepackage[T1]{fontenc,url}
5 \usepackage{lmodern} % using Latin Modern to be able to use bold typewriter font
9 \usepackage{tikz-qtree}
10 \usetikzlibrary{shapes,snakes,trees}
11 \usepackage{babel,textcomp,csquotes,ifimasterforside,varioref}
12 \usepackage[hidelinks]{hyperref}
14 \usepackage[style=numeric-comp,backend=bibtex]{biblatex}
17 % use 'disable' before printing:
18 \usepackage[]{todonotes}
25 \usepackage{perpage} %the perpage package
26 \MakePerPage{footnote} %the perpage package command
28 \theoremstyle{definition}
29 \newtheorem*{wordDef}{Definition}
31 \graphicspath{ {./figures/} }
33 \newcommand{\citing}[1]{~\cite{#1}}
34 \newcommand{\myref}[1]{\cref{#1} on \cpageref{#1}}
36 \newcommand{\definition}[1]{\begin{wordDef}#1\end{wordDef}}
37 \newcommand{\see}[1]{(see \myref{#1})}
38 \newcommand{\See}[1]{(See \myref{#1}.)}
39 \newcommand{\explanation}[3]{\noindent\textbf{\textit{#1}}\\*\emph{When:}
40 #2\\*\emph{How:} #3\\*[-7px]}
42 %\newcommand{\type}[1]{\lstinline{#1}}
43 \newcommand{\code}[1]{\texttt{\textbf{#1}}}
44 \newcommand{\type}[1]{\code{#1}}
45 \newcommand{\typeref}[1]{\footnote{\type{#1}}}
46 \newcommand{\typewithref}[2]{\type{#2}\typeref{#1.#2}}
47 \newcommand{\method}[1]{\type{#1}}
48 \newcommand{\methodref}[2]{\footnote{\type{#1}\method{\##2()}}}
49 \newcommand{\methodwithref}[2]{\method{#2}\footnote{\type{#1}\method{\##2()}}}
50 \newcommand{\var}[1]{\type{#1}}
52 \newcommand{\refactoring}[1]{\emph{#1}}
53 \newcommand{\ExtractMethod}{\refactoring{Extract Method}\xspace}
54 \newcommand{\MoveMethod}{\refactoring{Move Method}\xspace}
55 \newcommand{\ExtractAndMoveMethod}{\refactoring{Extract and Move Method}\xspace}
57 \newcommand\todoin[2][]{\todo[inline, caption={2do}, #1]{
58 \begin{minipage}{\textwidth-4pt}#2\end{minipage}}}
62 \author{Erlend Kristiansen}
64 \bibliography{bibliography/master-thesis-erlenkr-bibliography}
72 \todoin{\textbf{Remove all todos (including list) before delivery/printing!!!
73 Can be done by removing ``draft'' from documentclass.}}
74 \todoin{Write abstract}
82 The discussions in this report must be seen in the context of object oriented
83 programming languages, and Java in particular, since that is the language in
84 which most of the examples will be given. All though the techniques discussed
85 may be applicable to languages from other paradigms, they will not be the
86 subject of this report.
90 \chapter{What is Refactoring?}
92 This question is best answered by first defining the concept of a
93 \emph{refactoring}, what it is to \emph{refactor}, and then discuss what aspects
94 of programming make people want to refactor their code.
96 \section{Defining refactoring}
97 Martin Fowler, in his classic book on refactoring\citing{refactoring}, defines a
98 refactoring like this:
101 \emph{Refactoring} (noun): a change made to the internal
102 structure\footnote{The structure observable by the programmer.} of software to
103 make it easier to understand and cheaper to modify without changing its
104 observable behavior.~\cite[p.~53]{refactoring}
107 \noindent This definition assigns additional meaning to the word
108 \emph{refactoring}, beyond the composition of the prefix \emph{re-}, usually
109 meaning something like ``again'' or ``anew'', and the word \emph{factoring},
110 that can mean to isolate the \emph{factors} of something. Here a \emph{factor}
111 would be close to the mathematical definition of something that divides a
112 quantity, without leaving a remainder. Fowler is mixing the \emph{motivation}
113 behind refactoring into his definition. Instead it could be more refined, formed
114 to only consider the \emph{mechanical} and \emph{behavioral} aspects of
115 refactoring. That is to factor the program again, putting it together in a
116 different way than before, while preserving the behavior of the program. An
117 alternative definition could then be:
119 \definition{A \emph{refactoring} is a transformation
120 done to a program without altering its external behavior.}
122 From this we can conclude that a refactoring primarily changes how the
123 \emph{code} of a program is perceived by the \emph{programmer}, and not the
124 \emph{behavior} experienced by any user of the program. Although the logical
125 meaning is preserved, such changes could potentially alter the program's
126 behavior when it comes to performance gain or -penalties. So any logic depending
127 on the performance of a program could make the program behave differently after
130 In the extreme case one could argue that such a thing as \emph{software
131 obfuscation} is refactoring. Software obfuscation is to make source code harder
132 to read and analyze, while preserving its semantics. It could be done composing
133 many, more or less randomly chosen, refactorings. Then the question arise
134 whether it can be called a \emph{composite refactoring}
135 \see{compositeRefactorings} or not? The answer is not obvious. First, there is
136 no way to describe \emph{the} mechanics of software obfuscation, beacause there
137 are infinitely many ways to do that. Second, \emph{obfuscation} can be thought
138 of as \emph{one operation}: Either the code is obfuscated, or it is not. Third,
139 it makes no sense to call software obfuscation \emph{a} refactoring, since it
140 holds different meaning to different people. The last point is important, since
141 one of the motivations behind defining different refactorings is to build up a
142 vocabulary for software professionals to reason and discuss about programs,
143 similar to the motivation behind design patterns\citing{designPatterns}. So for
144 describing \emph{software obfuscation}, it might be more appropriate to define
145 what you do when performing it rather than precisely defining its mechanics in
146 terms of other refactorings.
148 \section{The etymology of 'refactoring'}
149 It is a little difficult to pinpoint the exact origin of the word
150 ``refactoring'', as it seems to have evolved as part of a colloquial
151 terminology, more than a scientific term. There is no authoritative source for a
152 formal definition of it.
154 According to Martin Fowler\citing{etymology-refactoring}, there may also be more
155 than one origin of the word. The most well-known source, when it comes to the
156 origin of \emph{refactoring}, is the Smalltalk\footnote{\emph{Smalltalk},
157 object-oriented, dynamically typed, reflective programming language. See
158 \url{http://www.smalltalk.org}} community and their infamous \emph{Refactoring
159 Browser}\footnote{\url{http://st-www.cs.illinois.edu/users/brant/Refactory/RefactoringBrowser.html}}
160 described in the article \emph{A Refactoring Tool for
161 Smalltalk}\citing{refactoringBrowser1997}, published in 1997.
162 Allegedly\citing{etymology-refactoring}, the metaphor of factoring programs was
163 also present in the Forth\footnote{\emph{Forth} -- stack-based, extensible
164 programming language, without type-checking. See \url{http://www.forth.org}}
165 community, and the word ``refactoring'' is mentioned in a book by Leo Brodie,
166 called \emph{Thinking Forth}\citing{brodie1984}, first published in
167 1984\footnote{\emph{Thinking Forth} was first published in 1984 by the
168 \emph{Forth Interest Group}. Then it was reprinted in 1994 with minor
169 typographical corrections, before it was transcribed into an electronic edition
170 typeset in \LaTeX\ and published under a Creative Commons licence in 2004. The
171 edition cited here is the 2004 edition, but the content should essentially be as
172 in 1984.}. The exact word is only printed one place~\cite[p.~232]{brodie1984},
173 but the term \emph{factoring} is prominent in the book, that also contains a
174 whole chapter dedicated to (re)factoring, and how to keep the (Forth) code clean
178 \ldots good factoring technique is perhaps the most important skill for a
179 Forth programmer.~\cite[p.~172]{brodie1984}
182 \noindent Brodie also express what \emph{factoring} means to him:
185 Factoring means organizing code into useful fragments. To make a fragment
186 useful, you often must separate reusable parts from non-reusable parts. The
187 reusable parts become new definitions. The non-reusable parts become arguments
188 or parameters to the definitions.~\cite[p.~172]{brodie1984}
191 Fowler claims that the usage of the word \emph{refactoring} did not pass between
192 the \emph{Forth} and \emph{Smalltalk} communities, but that it emerged
193 independently in each of the communities.
195 \section{Motivation -- Why people refactor}
196 There are many reasons why people want to refactor their programs. They can for
197 instance do it to remove duplication, break up long methods or to introduce
198 design patterns\citing{designPatterns} into their software systems. The shared
199 trait for all these are that peoples intentions are to make their programs
200 \emph{better}, in some sense. But what aspects of their programs are becoming
203 As already mentioned, people often refactor to get rid of duplication. Moving
204 identical or similar code into methods, and maybe pushing methods up or down in
205 their class hierarchies. Making template methods for overlapping
206 algorithms/functionality and so on. It is all about gathering what belongs
207 together and putting it all in one place. The resulting code is then easier to
208 maintain. When removing the implicit coupling\footnote{When duplicating code,
209 the code might not be coupled in other ways than that it is supposed to
210 represent the same functionality. So if this functionality is going to change,
211 it might need to change in more than one place, thus creating an implicit
212 coupling between the multiple pieces of code.} between code snippets, the
213 location of a bug is limited to only one place, and new functionality need only
214 to be added to this one place, instead of a number of places people might not
217 A problem you often encounter when programming, is that a program contains a lot
218 of long and hard-to-grasp methods. It can then help to break the methods into
219 smaller ones, using the \ExtractMethod refactoring\citing{refactoring}. Then you
220 may discover something about a program that you were not aware of before;
221 revealing bugs you did not know about or could not find due to the complex
222 structure of your program. \todo{Proof?} Making the methods smaller and giving
223 good names to the new ones clarifies the algorithms and enhances the
224 \emph{understandability} of the program \see{magic_number_seven}. This makes
225 refactoring an excellent method for exploring unknown program code, or code that
226 you had forgotten that you wrote.
228 Most primitive refactorings are simple. Their true power is first revealed when
229 they are combined into larger --- higher level --- refactorings, called
230 \emph{composite refactorings} \see{compositeRefactorings}. Often the goal of
231 such a series of refactorings is a design pattern. Thus the \emph{design} can be
232 evolved throughout the lifetime of a program, as opposed to designing up-front.
233 It is all about being structured and taking small steps to improve a program's
236 Many software design pattern are aimed at lowering the coupling between
237 different classes and different layers of logic. One of the most famous is
238 perhaps the \emph{Model-View-Controller}\citing{designPatterns} pattern. It is
239 aimed at lowering the coupling between the user interface and the business logic
240 and data representation of a program. This also has the added benefit that the
241 business logic could much easier be the target of automated tests, increasing
242 the productivity in the software development process. Refactoring is an
243 important tool on the way to something greater.
245 Another effect of refactoring is that with the increased separation of concerns
246 coming out of many refactorings, the \emph{performance} can be improved. When
247 profiling programs, the problematic parts are narrowed down to smaller parts of
248 the code, which are easier to tune, and optimization can be performed only where
249 needed and in a more effective way.
251 Last, but not least, and this should probably be the best reason to refactor, is
252 to refactor to \emph{facilitate a program change}. If one has managed to keep
253 one's code clean and tidy, and the code is not bloated with design patterns that
254 are not ever going to be needed, then some refactoring might be needed to
255 introduce a design pattern that is appropriate for the change that is going to
258 Refactoring program code --- with a goal in mind --- can give the code itself
259 more value. That is in the form of robustness to bugs, understandability and
260 maintainability. Having robust code is an obvious advantage, but
261 understandability and maintainability are both very important aspects of
262 software development. By incorporating refactoring in the development process,
263 bugs are found faster, new functionality is added more easily and code is easier
264 to understand by the next person exposed to it, which might as well be the
265 person who wrote it. The consequence of this, is that refactoring can increase
266 the average productivity of the development process, and thus also add to the
267 monetary value of a business in the long run. The perspective on productivity
268 and money should also be able to open the eyes of the many nearsighted managers
269 that seldom see beyond the next milestone.
271 \section{The magical number seven}\label{magic_number_seven}
272 The article \emph{The magical number seven, plus or minus two: some limits on
273 our capacity for processing information}\citing{miller1956} by George A.
274 Miller, was published in the journal \emph{Psychological Review} in 1956. It
275 presents evidence that support that the capacity of the number of objects a
276 human being can hold in its working memory is roughly seven, plus or minus two
277 objects. This number varies a bit depending on the nature and complexity of the
278 objects, but is according to Miller ``\ldots never changing so much as to be
281 Miller's article culminates in the section called \emph{Recoding}, a term he
282 borrows from communication theory. The central result in this section is that by
283 recoding information, the capacity of the amount of information that a human can
284 process at a time is increased. By \emph{recoding}, Miller means to group
285 objects together in chunks and give each chunk a new name that it can be
286 remembered by. By organizing objects into patterns of ever growing depth, one
287 can memorize and process a much larger amount of data than if it were to be
288 represented as its basic pieces. This grouping and renaming is analogous to how
289 many refactorings work, by grouping pieces of code and give them a new name.
290 Examples are the fundamental \ExtractMethod and \refactoring{Extract Class}
291 refactorings\citing{refactoring}.
294 \ldots recoding is an extremely powerful weapon for increasing the amount of
295 information that we can deal with.~\cite[p.~95]{miller1956}
298 An example from the article addresses the problem of memorizing a sequence of
299 binary digits. Let us say we have the following sequence\footnote{The example
300 presented here is slightly modified (and shortened) from what is presented in
301 the original article\citing{miller1956}, but it is essentially the same.} of
302 16 binary digits: ``1010001001110011''. Most of us will have a hard time
303 memorizing this sequence by only reading it once or twice. Imagine if we instead
304 translate it to this sequence: ``A273''. If you have a background from computer
305 science, it will be obvious that the latest sequence is the first sequence
306 recoded to be represented by digits with base 16. Most people should be able to
307 memorize this last sequence by only looking at it once.
309 Another result from the Miller article is that when the amount of information a
310 human must interpret increases, it is crucial that the translation from one code
311 to another must be almost automatic for the subject to be able to remember the
312 translation, before \heshe is presented with new information to recode. Thus
313 learning and understanding how to best organize certain kinds of data is
314 essential to efficiently handle that kind of data in the future. This is much
315 like when humans learn to read. First they must learn how to recognize letters.
316 Then they can learn distinct words, and later read sequences of words that form
317 whole sentences. Eventually, most of them will be able to read whole books and
318 briefly retell the important parts of its content. This suggest that the use of
319 design patterns\citing{designPatterns} is a good idea when reasoning about
320 computer programs. With extensive use of design patterns when creating complex
321 program structures, one does not always have to read whole classes of code to
322 comprehend how they function, it may be sufficient to only see the name of a
323 class to almost fully understand its responsibilities.
326 Our language is tremendously useful for repackaging material into a few chunks
327 rich in information.~\cite[p.~95]{miller1956}
330 Without further evidence, these results at least indicate that refactoring
331 source code into smaller units with higher cohesion and, when needed,
332 introducing appropriate design patterns, should aid in the cause of creating
333 computer programs that are easier to maintain and has code that is easier (and
336 \section{Notable contributions to the refactoring literature}
337 \todoin{Update with more contributions}
340 \item[1992] William F. Opdyke submits his doctoral dissertation called
341 \emph{Refactoring Object-Oriented Frameworks}\citing{opdyke1992}. This
342 work defines a set of refactorings, that are behavior preserving given that
343 their preconditions are met. The dissertation is focused on the automation
345 \item[1999] Martin Fowler et al.: \emph{Refactoring: Improving the Design of
346 Existing Code}\citing{refactoring}. This is maybe the most influential text
347 on refactoring. It bares similarities with Opdykes thesis\citing{opdyke1992}
348 in the way that it provides a catalog of refactorings. But Fowler's book is
349 more about the craft of refactoring, as he focuses on establishing a
350 vocabulary for refactoring, together with the mechanics of different
351 refactorings and when to perform them. His methodology is also founded on
352 the principles of test-driven development.
353 \item[2005] Joshua Kerievsky: \emph{Refactoring to
354 Patterns}\citing{kerievsky2005}. This book is heavily influenced by Fowler's
355 \emph{Refactoring}\citing{refactoring} and the ``Gang of Four'' \emph{Design
356 Patterns}\citing{designPatterns}. It is building on the refactoring
357 catalogue from Fowler's book, but is trying to bridge the gap between
358 \emph{refactoring} and \emph{design patterns} by providing a series of
359 higher-level composite refactorings, that makes code evolve toward or away
360 from certain design patterns. The book is trying to build up the readers
361 intuition around \emph{why} one would want to use a particular design
362 pattern, and not just \emph{how}. The book is encouraging evolutionary
363 design. \See{relationToDesignPatterns}
366 \section{Tool support (for Java)}\label{toolSupport}
367 This section will briefly compare the refatoring support of the three IDEs
368 \emph{Eclipse}\footnote{\url{http://www.eclipse.org/}}, \emph{IntelliJ
369 IDEA}\footnote{The IDE under comparison is the \emph{Community Edition},
370 \url{http://www.jetbrains.com/idea/}} and
371 \emph{NetBeans}\footnote{\url{https://netbeans.org/}}. These are the most
372 popular Java IDEs\citing{javaReport2011}.
374 All three IDEs provide support for the most useful refactorings, like the
375 different extract, move and rename refactorings. In fact, Java-targeted IDEs are
376 known for their good refactoring support, so this did not appear as a big
379 The IDEs seem to have excellent support for the \ExtractMethod refactoring, so
380 at least they have all passed the first refactoring
381 rubicon\citing{fowlerRubicon2001,secondRubicon2012}.
383 Regarding the \MoveMethod refactoring, the \emph{Eclipse} and \emph{IntelliJ}
384 IDEs do the job in very similar manners. In most situations they both do a
385 satisfying job by producing the expected outcome. But they do nothing to check
386 that the result does not break the semantics of the program \see{correctness}.
387 The \emph{NetBeans} IDE implements this refactoring in a somewhat
388 unsophisticated way. For starters, its default destination for the move is
389 itself, although it refuses to perform the refactoring if chosen. But the worst
390 part is, that if moving the method \method{f} of the class \type{C} to the class
391 \type{X}, it will break the code. The result is shown in
392 \myref{lst:moveMethod_NetBeans}.
396 \begin{minted}[samepage]{java}
409 \begin{minted}[samepage]{java}
419 \caption{Moving method \method{f} from \type{C} to \type{X}.}
420 \label{lst:moveMethod_NetBeans}
423 NetBeans will try to make code that call the methods \method{m} and \method{n}
424 of \type{X} by accessing them through \var{c.x}, where \var{c} is a parameter of
425 type \type{C} that is added the method \method{f} when it is moved. (This is
426 seldom the desired outcome of this refactoring, but ironically, this ``feature''
427 keeps NetBeans from breaking the code in the example from \myref{correctness}.)
428 If \var{c.x} for some reason is inaccessible to \type{X}, as in this case, the
429 refactoring breaks the code, and it will not compile. NetBeans presents a
430 preview of the refactoring outcome, but the preview does not catch it if the IDE
431 is about break the program.
433 The IDEs under investigation seems to have fairly good support for primitive
434 refactorings, but what about more complex ones, such as the \refactoring{Extract
435 Class}\citing{refactoring}? The \refactoring{Extract Class} refactoring works by
436 creating a class, for then to move members to that class and access them from
437 the old class via a reference to the new class. \emph{IntelliJ} handles this in
438 a fairly good manner, although, in the case of private methods, it leaves unused
439 methods behind. These are methods that delegate to a field with the type of the
440 new class, but are not used anywhere. \emph{Eclipse} has added (or withdrawn)
441 its own quirk to the Extract Class refactoring, and only allows for
442 \emph{fields} to be moved to a new class, \emph{not methods}. This makes it
443 effectively only extracting a data structure, and calling it
444 \refactoring{Extract Class} is a little misleading. One would often be better
445 off with textual extract and paste than using the Extract Class refactoring in
446 Eclipse. When it comes to \emph{NetBeans}, it does not even seem to have made an
447 attempt on providing this refactoring. (Well, it probably has, but it does not
450 \todoin{Visual Studio (C++/C\#), Smalltalk refactoring browser?,
451 second refactoring rubicon?}
453 \section{The relation to design patterns}\label{relationToDesignPatterns}
455 \emph{Refactoring} and \emph{design patterns} have at least one thing in common,
456 they are both promoted by advocates of \emph{clean code}\citing{cleanCode} as
457 fundamental tools on the road to more maintanable and extendable source code.
460 Design patterns help you determine how to reorganize a design, and they can
461 reduce the amount of refactoring you need to do
462 later.~\cite[p.~353]{designPatterns}
465 Although sometimes associated with
466 over-engineering\citing{kerievsky2005,refactoring}, design patterns are in
467 general assumed to be good for maintainability of source code. That may be
468 because many of them are designed to support the \emph{open/closed principle} of
469 object-oriented programming. The principle was first formulated by Bertrand
470 Meyer, the creator of the Eiffel programming language, like this: ``Modules
471 should be both open and closed.''\citing{meyer1988} It has been popularized,
472 with this as a common version:
475 Software entities (classes, modules, functions, etc.) should be open for
476 extension, but closed for modification.\footnote{See
477 \url{http://c2.com/cgi/wiki?OpenClosedPrinciple} or
478 \url{https://en.wikipedia.org/wiki/Open/closed_principle}}
481 Maintainability is often thought of as the ability to be able to introduce new
482 functionality without having to change too much of the old code. When
483 refactoring, the motivation is often to facilitate adding new functionality. It
484 is about factoring the old code in a way that makes the new functionality being
485 able to benefit from the functionality already residing in a software system,
486 without having to copy old code into new. Then, next time someone shall add new
487 functionality, it is less likely that the old code has to change. Assuming that
488 a design pattern is the best way to get rid of duplication and assist in
489 implementing new functionality, it is reasonable to conclude that a design
490 pattern often is the target of a series of refactorings. Having a repertoire of
491 design patterns can also help in knowing when and how to refactor a program to
492 make it reflect certain desired characteristics.
495 There is a natural relation between patterns and refactorings. Patterns are
496 where you want to be; refactorings are ways to get there from somewhere
497 else.~\cite[p.~107]{refactoring}
500 This quote is wise in many contexts, but it is not always appropriate to say
501 ``Patterns are where you want to be\ldots''. \emph{Sometimes}, patterns are
502 where you want to be, but only because it will benefit your design. It is not
503 true that one should always try to incorporate as many design patterns as
504 possible into a program. It is not like they have intrinsic value. They only add
505 value to a system when they support its design. Otherwise, the use of design
506 patterns may only lead to a program that is more complex than necessary.
509 The overuse of patterns tends to result from being patterns happy. We are
510 \emph{patterns happy} when we become so enamored of patterns that we simply
511 must use them in our code.~\cite[p.~24]{kerievsky2005}
514 This can easily happen when relying largely on up-front design. Then it is
515 natural, in the very beginning, to try to build in all the flexibility that one
516 believes will be necessary throughout the lifetime of a software system.
517 According to Joshua Kerievsky ``That sounds reasonable --- if you happen to be
518 psychic.''~\cite[p.~1]{kerievsky2005} He is advocating what he believes is a
519 better approach: To let software continually evolve. To start with a simple
520 design that meets today's needs, and tackle future needs by refactoring to
521 satisfy them. He believes that this is a more economic approach than investing
522 time and money into a design that inevitably is going to change. By relying on
523 continuously refactoring a system, its design can be made simpler without
524 sacrificing flexibility. To be able to fully rely on this approach, it is of
525 utter importance to have a reliable suit of tests to lean on. \See{testing} This
526 makes the design process more natural and less characterized by difficult
527 decisions that has to be made before proceeding in the process, and that is
528 going to define a project for all of its unforeseeable future.
532 \section{Classification of refactorings}
533 % only interesting refactorings
534 % with 2 detailed examples? One for structured and one for intra-method?
535 % Is replacing Bubblesort with Quick Sort considered a refactoring?
537 \subsection{Structural refactorings}
539 \subsubsection{Primitive refactorings}
542 \explanation{Extract Method}{You have a code fragment that can be grouped
543 together.}{Turn the fragment into a method whose name explains the purpose of
546 \explanation{Inline Method}{A method's body is just as clear as its name.}{Put
547 the method's body into the body of its callers and remove the method.}
549 \explanation{Inline Temp}{You have a temp that is assigned to once with a simple
550 expression, and the temp is getting in the way of other refactorings.}{Replace
551 all references to that temp with the expression}
553 % Moving Features Between Objects
554 \explanation{Move Method}{A method is, or will be, using or used by more
555 features of another class than the class on which it is defined.}{Create a new
556 method with a similar body in the class it uses most. Either turn the old method
557 into a simple delegation, or remove it altogether.}
559 \explanation{Move Field}{A field is, or will be, used by another class more than
560 the class on which it is defined}{Create a new field in the target class, and
561 change all its users.}
564 \explanation{Replace Magic Number with Symbolic Constant}{You have a literal
565 number with a particular meaning.}{Create a constant, name it after the meaning,
566 and replace the number with it.}
568 \explanation{Encapsulate Field}{There is a public field.}{Make it private and
571 \explanation{Replace Type Code with Class}{A class has a numeric type code that
572 does not affect its behavior.}{Replace the number with a new class.}
574 \explanation{Replace Type Code with Subclasses}{You have an immutable type code
575 that affects the behavior of a class.}{Replace the type code with subclasses.}
577 \explanation{Replace Type Code with State/Strategy}{You have a type code that
578 affects the behavior of a class, but you cannot use subclassing.}{Replace the
579 type code with a state object.}
581 % Simplifying Conditional Expressions
582 \explanation{Consolidate Duplicate Conditional Fragments}{The same fragment of
583 code is in all branches of a conditional expression.}{Move it outside of the
586 \explanation{Remove Control Flag}{You have a variable that is acting as a
587 control flag fro a series of boolean expressions.}{Use a break or return
590 \explanation{Replace Nested Conditional with Guard Clauses}{A method has
591 conditional behavior that does not make clear the normal path of
592 execution.}{Use guard clauses for all special cases.}
594 \explanation{Introduce Null Object}{You have repeated checks for a null
595 value.}{Replace the null value with a null object.}
597 \explanation{Introduce Assertion}{A section of code assumes something about the
598 state of the program.}{Make the assumption explicit with an assertion.}
600 % Making Method Calls Simpler
601 \explanation{Rename Method}{The name of a method does not reveal its
602 purpose.}{Change the name of the method}
604 \explanation{Add Parameter}{A method needs more information from its
605 caller.}{Add a parameter for an object that can pass on this information.}
607 \explanation{Remove Parameter}{A parameter is no longer used by the method
610 %\explanation{Parameterize Method}{Several methods do similar things but with
611 %different values contained in the method.}{Create one method that uses a
612 %parameter for the different values.}
614 \explanation{Preserve Whole Object}{You are getting several values from an
615 object and passing these values as parameters in a method call.}{Send the whole
618 \explanation{Remove Setting Method}{A field should be set at creation time and
619 never altered.}{Remove any setting method for that field.}
621 \explanation{Hide Method}{A method is not used by any other class.}{Make the
624 \explanation{Replace Constructor with Factory Method}{You want to do more than
625 simple construction when you create an object}{Replace the constructor with a
628 % Dealing with Generalization
629 \explanation{Pull Up Field}{Two subclasses have the same field.}{Move the field
632 \explanation{Pull Up Method}{You have methods with identical results on
633 subclasses.}{Move them to the superclass.}
635 \explanation{Push Down Method}{Behavior on a superclass is relevant only for
636 some of its subclasses.}{Move it to those subclasses.}
638 \explanation{Push Down Field}{A field is used only by some subclasses.}{Move the
639 field to those subclasses}
641 \explanation{Extract Interface}{Several clients use the same subset of a class's
642 interface, or two classes have part of their interfaces in common.}{Extract the
643 subset into an interface.}
645 \explanation{Replace Inheritance with Delegation}{A subclass uses only part of a
646 superclasses interface or does not want to inherit data.}{Create a field for the
647 superclass, adjust methods to delegate to the superclass, and remove the
650 \explanation{Replace Delegation with Inheritance}{You're using delegation and
651 are often writing many simple delegations for the entire interface}{Make the
652 delegating class a subclass of the delegate.}
654 \subsubsection{Composite refactorings}
657 % \explanation{Replace Method with Method Object}{}{}
659 % Moving Features Between Objects
660 \explanation{Extract Class}{You have one class doing work that should be done by
661 two}{Create a new class and move the relevant fields and methods from the old
662 class into the new class.}
664 \explanation{Inline Class}{A class isn't doing very much.}{Move all its features
665 into another class and delete it.}
667 \explanation{Hide Delegate}{A client is calling a delegate class of an
668 object.}{Create Methods on the server to hide the delegate.}
670 \explanation{Remove Middle Man}{A class is doing to much simple delegation.}{Get
671 the client to call the delegate directly.}
674 \explanation{Replace Data Value with Object}{You have a data item that needs
675 additional data or behavior.}{Turn the data item into an object.}
677 \explanation{Change Value to Reference}{You have a class with many equal
678 instances that you want to replace with a single object.}{Turn the object into a
681 \explanation{Encapsulate Collection}{A method returns a collection}{Make it
682 return a read-only view and provide add/remove methods.}
684 % \explanation{Replace Array with Object}{}{}
686 \explanation{Replace Subclass with Fields}{You have subclasses that vary only in
687 methods that return constant data.}{Change the methods to superclass fields and
688 eliminate the subclasses.}
690 % Simplifying Conditional Expressions
691 \explanation{Decompose Conditional}{You have a complicated conditional
692 (if-then-else) statement.}{Extract methods from the condition, then part, an
695 \explanation{Consolidate Conditional Expression}{You have a sequence of
696 conditional tests with the same result.}{Combine them into a single conditional
697 expression and extract it.}
699 \explanation{Replace Conditional with Polymorphism}{You have a conditional that
700 chooses different behavior depending on the type of an object.}{Move each leg
701 of the conditional to an overriding method in a subclass. Make the original
704 % Making Method Calls Simpler
705 \explanation{Replace Parameter with Method}{An object invokes a method, then
706 passes the result as a parameter for a method. The receiver can also invoke this
707 method.}{Remove the parameter and let the receiver invoke the method.}
709 \explanation{Introduce Parameter Object}{You have a group of parameters that
710 naturally go together.}{Replace them with an object.}
712 % Dealing with Generalization
713 \explanation{Extract Subclass}{A class has features that are used only in some
714 instances.}{Create a subclass for that subset of features.}
716 \explanation{Extract Superclass}{You have two classes with similar
717 features.}{Create a superclass and move the common features to the
720 \explanation{Collapse Hierarchy}{A superclass and subclass are not very
721 different.}{Merge them together.}
723 \explanation{Form Template Method}{You have two methods in subclasses that
724 perform similar steps in the same order, yet the steps are different.}{Get the
725 steps into methods with the same signature, so that the original methods become
726 the same. Then you can pull them up.}
729 \subsection{Functional refactorings}
731 \explanation{Substitute Algorithm}{You want to replace an algorithm with one
732 that is clearer.}{Replace the body of the method with the new algorithm.}
736 \section{The impact on software quality}
738 \subsection{What is software quality?}
739 The term \emph{software quality} has many meanings. It all depends on the
740 context we put it in. If we look at it with the eyes of a software developer, it
741 usually means that the software is easily maintainable and testable, or in other
742 words, that it is \emph{well designed}. This often correlates with the
743 management scale, where \emph{keeping the schedule} and \emph{customer
744 satisfaction} is at the center. From the customers point of view, in addition to
745 good usability, \emph{performance} and \emph{lack of bugs} is always
746 appreciated, measurements that are also shared by the software developer. (In
747 addition, such things as good documentation could be measured, but this is out
748 of the scope of this document.)
750 \subsection{The impact on performance}
752 Refactoring certainly will make software go more slowly\footnote{With todays
753 compiler optimization techniques and performance tuning of e.g. the Java
754 virtual machine, the penalties of object creation and method calls are
755 debatable.}, but it also makes the software more amenable to performance
756 tuning.~\cite[p.~69]{refactoring}
759 \noindent There is a common belief that refactoring compromises performance, due
760 to increased degree of indirection and that polymorphism is slower than
763 In a survey, Demeyer\citing{demeyer2002} disproves this view in the case of
764 polymorphism. He did an experiment on, what he calls, ``Transform Self Type
765 Checks'' where you introduce a new polymorphic method and a new class hierarchy
766 to get rid of a class' type checking of a ``type attribute``. He uses this kind
767 of transformation to represent other ways of replacing conditionals with
768 polymorphism as well. The experiment is performed on the C++ programming
769 language and with three different compilers and platforms. Demeyer concludes
770 that, with compiler optimization turned on, polymorphism beats middle to large
771 sized if-statements and does as well as case-statements. (In accordance with
772 his hypothesis, due to similarities between the way C++ handles polymorphism and
776 The interesting thing about performance is that if you analyze most programs,
777 you find that they waste most of their time in a small fraction of the
778 code.~\cite[p.~70]{refactoring}
781 \noindent So, although an increased amount of method calls could potentially
782 slow down programs, one should avoid premature optimization and sacrificing good
783 design, leaving the performance tuning until after profiling\footnote{For and
784 example of a Java profiler, check out VisualVM:
785 \url{http://visualvm.java.net/}} the software and having isolated the actual
788 \section{Composite refactorings}\label{compositeRefactorings}
789 \todo{motivation, examples, manual vs automated?, what about refactoring in a
790 very large code base?}
791 Generally, when thinking about refactoring, at the mechanical level, there are
792 essentially two kinds of refactorings. There are the \emph{primitive}
793 refactorings, and the \emph{composite} refactorings.
795 \definition{A \emph{primitive refactoring} is a refactoring that cannot be
796 expressed in terms of other refactorings.}
798 \noindent Examples are the \refactoring{Pull Up Field} and \refactoring{Pull Up
799 Method} refactorings\citing{refactoring}, that move members up in their class
802 \definition{A \emph{composite refactoring} is a refactoring that can be
803 expressed in terms of two or more other refactorings.}
805 \noindent An example of a composite refactoring is the \refactoring{Extract
806 Superclass} refactoring\citing{refactoring}. In its simplest form, it is composed
807 of the previously described primitive refactorings, in addition to the
808 \refactoring{Pull Up Constructor Body} refactoring\citing{refactoring}. It works
809 by creating an abstract superclass that the target class(es) inherits from, then
810 by applying \refactoring{Pull Up Field}, \refactoring{Pull Up Method} and
811 \refactoring{Pull Up Constructor Body} on the members that are to be members of
812 the new superclass. For an overview of the \refactoring{Extract Superclass}
813 refactoring, see \myref{fig:extractSuperclass}.
817 \includegraphics[angle=270,width=\linewidth]{extractSuperclassItalic.pdf}
818 \caption{The Extract Superclass refactoring}
819 \label{fig:extractSuperclass}
822 \section{Manual vs. automated refactorings}
823 Refactoring is something every programmer does, even if \heshe does not known
824 the term \emph{refactoring}. Every refinement of source code that does not alter
825 the program's behavior is a refactoring. For small refactorings, such as
826 \ExtractMethod, executing it manually is a manageable task, but is still prone
827 to errors. Getting it right the first time is not easy, considering the method
828 signature and all the other aspects of the refactoring that has to be in place.
830 Take for instance the renaming of classes, methods and fields. For complex
831 programs these refactorings are almost impossible to get right. Attacking them
832 with textual search and replace, or even regular expressions, will fall short on
833 these tasks. Then it is crucial to have proper tool support that can perform
834 them automatically. Tools that can parse source code and thus have semantic
835 knowledge about which occurrences of which names belong to what construct in the
836 program. For even trying to perform one of these complex task manually, one
837 would have to be very confident on the existing test suite \see{testing}.
839 \section{Correctness of refactorings}\label{correctness}
840 For automated refactorings to be truly useful, they must show a high degree of
841 behavior preservation. This last sentence might seem obvious, but there are
842 examples of refactorings in existing tools that break programs. I will now
843 present an example of an \ExtractMethod refactoring followed by a \MoveMethod
844 refactoring that breaks a program in both the \emph{Eclipse} and \emph{IntelliJ}
845 IDEs\footnote{The NetBeans IDE handles this particular situation without
846 altering ther program's beavior, mainly because its Move Method refactoring
847 implementation is a bit rancid in other ways \see{toolSupport}.}. The
848 following piece of code shows the target for the composed refactoring:
850 \begin{minted}[linenos,samepage]{java}
852 public X x = new X();
861 \noindent The next piece of code shows the destination of the refactoring. Note
862 that the method \method{m(C c)} of class \type{C} assigns to the field \var{x}
863 of the argument \var{c} that has type \type{C}:
865 \begin{minted}[samepage]{java}
874 The refactoring sequence works by extracting line 5 and 6 from the original
875 class \type{C} into a method \method{f} with the statements from those lines as
876 its method body. The method is then moved to the class \type{X}. The result is
877 shown in the following two pieces of code:
879 \begin{minted}[linenos,samepage]{java}
881 public X x = new X();
889 \begin{minted}[linenos,samepage]{java}
902 After the refactoring, the method \method{f} of class \type{C} is calling the
903 method \method{f} of class \type{X}, and the program now behaves different than
904 before. (See line 5 of the version of class \type{C} after the refactoring.)
905 Before the refactoring, the methods \method{m} and \method{n} of class \type{X}
906 are called on different object instances (see line 5 and 6 of the original class
907 \type{C}). After, they are called on the same object, and the statement on line
908 3 of class \type{X} (the version after the refactoring) no longer have any
909 effect in our example.
911 The bug introduced in the previous example is of such a nature\footnote{Caused
912 by aliasing. See \url{https://en.wikipedia.org/wiki/Aliasing_(computing)}}
913 that it is very difficult to spot if the refactored code is not covered by
914 tests. It does not generate compilation errors, and will thus only result in
915 a runtime error or corrupted data, which might be hard to detect.
917 \section{Refactoring and the importance of testing}\label{testing}
919 If you want to refactor, the essential precondition is having solid
920 tests.\citing{refactoring}
923 When refactoring, there are roughly three classes of errors that can be made.
924 The first class of errors are the ones that make the code unable to compile.
925 These \emph{compile-time} errors are of the nicer kind. They flash up at the
926 moment they are made (at least when using an IDE), and are usually easy to fix.
927 The second class are the \emph{runtime} errors. Although they take a bit longer
928 to surface, they usually manifest after some time in an illegal argument
929 exception, null pointer exception or similar during the program execution.
930 These kind of errors are a bit harder to handle, but at least they will show,
931 eventually. Then there are the \emph{behavior-changing} errors. These errors are
932 of the worst kind. They do not show up during compilation and they do not turn
933 on a blinking red light during runtime either. The program can seem to work
934 perfectly fine with them in play, but the business logic can be damaged in ways
935 that will only show up over time.
937 For discovering runtime errors and behavior changes when refactoring, it is
938 essential to have good test coverage. Testing in this context means writing
939 automated tests. Manual testing may have its uses, but when refactoring, it is
940 automated unit testing that dominate. For discovering behavior changes it is
941 especially important to have tests that cover potential problems, since these
942 kind of errors does not reveal themselves.
944 Unit testing is not a way to \emph{prove} that a program is correct, but it is a
945 way to make you confindent that it \emph{probably} works as desired. In the
946 context of test driven development (commonly known as TDD), the tests are even a
947 way to define how the program is \emph{supposed} to work. It is then, by
948 definition, working if the tests are passing.
950 If the test coverage for a code base is perfect, then it should, theoretically,
951 be risk-free to perform refactorings on it. This is why automated tests and
952 refactoring are such a great match.
954 \subsection{Testing the code from correctness section}
955 The worst thing that can happen when refactoring is to introduce changes to the
956 behavior of a program, as in the example on \myref{correctness}. This example
957 may be trivial, but the essence is clear. The only problem with the example is
958 that it is not clear how to create automated tests for it, without changing it
961 Unit tests, as they are known from the different xUnit frameworks around, are
962 only suitable to test the \emph{result} of isolated operations. They can not
963 easily (if at all) observe the \emph{history} of a program.
966 \todoin{Write \ldots}
968 Assuming a sequential (non-concurrent) program:
971 tracematch (C c, X x) {
973 call(* X.m(C)) && args(c) && cflow(within(C));
975 call(* X.n()) && target(x) && cflow(within(C));
977 set(C.x) && target(c) && !cflow(m);
985 %\begin{minted}{java}
986 %tracematch (X x1, X x2) {
988 % call(* X.m(C)) && target(x1);
990 % call(* X.n()) && target(x2);
992 % set(C.x) && !cflow(m) && !cflow(n);
996 % { assert x1 != x2; }
1000 \section{The project}
1001 The aim of this project will be to investigate the relationship between a
1002 composite refactoring composed of the \ExtractMethod and \MoveMethod
1003 refactorings, and its impact on one or more software metrics.
1005 The composition of \ExtractMethod and \MoveMethod springs naturally out of the
1006 need to move procedures closer to the data they manipulate. This composed
1007 refactoring is not well described in the literature, but it is implemented in at
1008 least one tool called
1009 \emph{CodeRush}\footnote{\url{https://help.devexpress.com/\#CodeRush/CustomDocument3519}},
1010 that is an extension for \emph{MS Visual
1011 Studio}\footnote{\url{http://www.visualstudio.com/}}. In CodeRush it is called
1012 \emph{Extract Method to
1013 Type}\footnote{\url{https://help.devexpress.com/\#CodeRush/CustomDocument6710}},
1014 but I choose to call it \ExtractAndMoveMethod, since I feel it better
1015 communicates which primitive refactorings it is composed of.
1017 For the metrics, I will at least measure the \emph{Coupling between object
1018 classes} (CBO) metric that is described by Chidamber and Kemerer in their
1019 article \emph{A Metrics Suite for Object Oriented
1020 Design}\citing{metricsSuite1994}.
1022 The project will then consist in implementing the \ExtractAndMoveMethod
1023 refactoring, as well as executing it over a larger code base. Then the effect of
1024 the change must be measured by calculating the chosen software metrics both
1025 before and after the execution. To be able to execute the refactoring
1026 automatically I have to make it analyze code to determine the best selections to
1027 extract into new methods.
1029 \section{Software metrics}
1030 \todoin{Is this the appropriate place to have this section?}
1033 %\chapter{Planning the project}
1041 \section{The problem statement}
1042 \section{Choosing the target language}
1043 Choosing which programming language to use as the target for manipulation is not
1044 a very difficult task. The language has to be an object-oriented programming
1045 language, and it must have existing tool support for refactoring. The
1046 \emph{Java} programming language\footnote{\url{https://www.java.com/}} is the
1047 dominating language when it comes to examples in the literature of refactoring,
1048 and is thus a natural choice. Java is perhaps, currently the most influential
1049 programming language in the world, with its \emph{Java Virtual Machine} that
1050 runs on all of the most popular architectures and also supports\footnote{They
1051 compile to java bytecode.} dozens of other programming languages, with
1052 \emph{Scala}, \emph{Clojure} and \emph{Groovy} as the most prominent ones. Java
1053 is currently the language that every other programming language is compared
1054 against. It is also the primary language of the author of this thesis.
1056 \section{Choosing the tools}
1057 When choosing a tool for manipulating Java, there are certain criterias that
1058 have to be met. First of all, the tool should have some existing refactoring
1059 support that this thesis can build upon. Secondly it should provide some kind of
1060 framework for parsing and analyzing Java source code. Third, it should itself be
1061 open source. This is both because of the need to be able to browse the code for
1062 the existing refactorings that is contained in the tool, and also because open
1063 source projects hold value in them selves. Another important aspect to consider
1064 is that open source projects of a certain size, usually has large communities of
1065 people connected to them, that are commited to answering questions regarding the
1066 use and misuse of the products, that to a large degree is made by the cummunity
1069 There is a certain class of tools that meet these criterias, namely the class of
1070 \emph{IDEs}\footnote{\emph{Integrated Development Environment}}. These are
1071 proagrams that is ment to support the whole production cycle of a cumputer
1072 program, and the most popular IDEs that support Java, generally have quite good
1073 refactoring support.
1075 The main contenders for this thesis is the \emph{Eclipse IDE}, with the
1076 \emph{Java development tools} (JDT), the \emph{IntelliJ IDEA Community Edition}
1077 and the \emph{NetBeans IDE}. \See{toolSupport} Eclipse and NetBeans are both
1078 free, open source and community driven, while the IntelliJ IDEA has an open
1079 sourced community edition that is free of charge, but also offer an
1080 \emph{Ultimate Edition} with an extended set of features, at additional cost.
1081 All three IDEs supports adding plugins to extend their functionality and tools
1082 that can be used to parse and analyze Java source code. But one of the IDEs
1083 stand out as a favorite, and that is the \emph{Eclipse IDE}. This is the most
1084 popular\citing{javaReport2011} among them and seems to be de facto standard IDE
1085 for Java development regardless of platform.
1088 \chapter{Refactorings in Eclipse JDT: Design, Shortcomings and Wishful
1089 Thinking}\label{ch:jdt_refactorings}
1091 This chapter will deal with some of the design behind refactoring support in
1092 Eclipse, and the JDT in specific. After which it will follow a section about
1093 shortcomings of the refactoring API in terms of composition of refactorings. The
1094 chapter will be concluded with a section telling some of the ways the
1095 implementation of refactorings in the JDT could have worked to facilitate
1096 composition of refactorings.
1099 The refactoring world of Eclipse can in general be separated into two parts: The
1100 language independent part and the part written for a specific programming
1101 language -- the language that is the target of the supported refactorings.
1102 \todo{What about the language specific part?}
1104 \subsection{The Language Toolkit}
1105 The Language Toolkit, or LTK for short, is the framework that is used to
1106 implement refactorings in Eclipse. It is language independent and provides the
1107 abstractions of a refactoring and the change it generates, in the form of the
1108 classes \typewithref{org.eclipse.ltk.core.refactoring}{Refactoring} and
1109 \typewithref{org.eclipse.ltk.core.refactoring}{Change}. (There is also parts of
1110 the LTK that is concerned with user interaction, but they will not be discussed
1111 here, since they are of little value to us and our use of the framework.)
1113 \subsubsection{The Refactoring Class}
1114 The abstract class \type{Refactoring} is the core of the LTK framework. Every
1115 refactoring that is going to be supported by the LTK have to end up creating an
1116 instance of one of its subclasses. The main responsibilities of subclasses of
1117 \type{Refactoring} is to implement template methods for condition checking
1118 (\methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{checkInitialConditions}
1120 \methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{checkFinalConditions}),
1122 \methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{createChange}
1123 method that creates and returns an instance of the \type{Change} class.
1125 If the refactoring shall support that others participate in it when it is
1126 executed, the refactoring has to be a processor-based
1127 refactoring\typeref{org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring}.
1128 It then delegates to its given
1129 \typewithref{org.eclipse.ltk.core.refactoring.participants}{RefactoringProcessor}
1130 for condition checking and change creation.
1132 \subsubsection{The Change Class}
1133 This class is the base class for objects that is responsible for performing the
1134 actual workspace transformations in a refactoring. The main responsibilities for
1135 its subclasses is to implement the
1136 \methodwithref{org.eclipse.ltk.core.refactoring.Change}{perform} and
1137 \methodwithref{org.eclipse.ltk.core.refactoring.Change}{isValid} methods. The
1138 \method{isValid} method verifies that the change object is valid and thus can be
1139 executed by calling its \method{perform} method. The \method{perform} method
1140 performs the desired change and returns an undo change that can be executed to
1141 reverse the effect of the transformation done by its originating change object.
1143 \subsubsection{Executing a Refactoring}\label{executing_refactoring}
1144 The life cycle of a refactoring generally follows two steps after creation:
1145 condition checking and change creation. By letting the refactoring object be
1147 \typewithref{org.eclipse.ltk.core.refactoring}{CheckConditionsOperation} that
1148 in turn is handled by a
1149 \typewithref{org.eclipse.ltk.core.refactoring}{CreateChangeOperation}, it is
1150 assured that the change creation process is managed in a proper manner.
1152 The actual execution of a change object has to follow a detailed life cycle.
1153 This life cycle is honored if the \type{CreateChangeOperation} is handled by a
1154 \typewithref{org.eclipse.ltk.core.refactoring}{PerformChangeOperation}. If also
1155 an undo manager\typeref{org.eclipse.ltk.core.refactoring.IUndoManager} is set
1156 for the \type{PerformChangeOperation}, the undo change is added into the undo
1159 \section{Shortcomings}
1160 This section is introduced naturally with a conclusion: The JDT refactoring
1161 implementation does not facilitate composition of refactorings.
1162 \todo{refine}This section will try to explain why, and also identify other
1163 shortcomings of both the usability and the readability of the JDT refactoring
1166 I will begin at the end and work my way toward the composition part of this
1169 \subsection{Absence of Generics in Eclipse Source Code}
1170 This section is not only concerning the JDT refactoring API, but also large
1171 quantities of the Eclipse source code. The code shows a striking absence of the
1172 Java language feature of generics. It is hard to read a class' interface when
1173 methods return objects or takes parameters of raw types such as \type{List} or
1174 \type{Map}. This sometimes results in having to read a lot of source code to
1175 understand what is going on, instead of relying on the available interfaces. In
1176 addition, it results in a lot of ugly code, making the use of typecasting more
1177 of a rule than an exception.
1179 \subsection{Composite Refactorings Will Not Appear as Atomic Actions}
1181 \subsubsection{Missing Flexibility from JDT Refactorings}
1182 The JDT refactorings are not made with composition of refactorings in mind. When
1183 a JDT refactoring is executed, it assumes that all conditions for it to be
1184 applied successfully can be found by reading source files that has been
1185 persisted to disk. They can only operate on the actual source material, and not
1186 (in-memory) copies thereof. This constitutes a major disadvantage when trying to
1187 compose refactorings, since if an exception occur in the middle of a sequence of
1188 refactorings, it can leave the project in a state where the composite
1189 refactoring was executed only partly. It makes it hard to discard the changes
1190 done without monitoring and consulting the undo manager, an approach that is not
1193 \subsubsection{Broken Undo History}
1194 When designing a composed refactoring that is to be performed as a sequence of
1195 refactorings, you would like it to appear as a single change to the workspace.
1196 This implies that you would also like to be able to undo all the changes done by
1197 the refactoring in a single step. This is not the way it appears when a sequence
1198 of JDT refactorings is executed. It leaves the undo history filled up with
1199 individual undo actions corresponding to every single JDT refactoring in the
1200 sequence. This problem is not trivial to handle in Eclipse.
1201 \See{hacking_undo_history}
1203 \section{Wishful Thinking}
1206 \chapter{Composite Refactorings in Eclipse}
1208 \section{A Simple Ad Hoc Model}
1209 As pointed out in \myref{ch:jdt_refactorings}, the Eclipse JDT refactoring model
1210 is not very well suited for making composite refactorings. Therefore a simple
1211 model using changer objects (of type \type{RefaktorChanger}) is used as an
1212 abstraction layer on top of the existing Eclipse refactorings, instead of
1213 extending the \typewithref{org.eclipse.ltk.core.refactoring}{Refactoring} class.
1215 The use of an additional abstraction layer is a deliberate choice. It is due to
1216 the problem of creating a composite
1217 \typewithref{org.eclipse.ltk.core.refactoring}{Change} that can handle text
1218 changes that interfere with each other. Thus, a \type{RefaktorChanger} may, or
1219 may not, take advantage of one or more existing refactorings, but it is always
1220 intended to make a change to the workspace.
1222 \subsection{A typical \type{RefaktorChanger}}
1223 The typical refaktor changer class has two responsibilities, checking
1224 preconditions and executing the requested changes. This is not too different
1225 from the responsibilities of an LTK refactoring, with the distinction that a
1226 refaktor changer also executes the change, while an LTK refactoring is only
1227 responsible for creating the object that can later be used to do the job.
1229 Checking of preconditions is typically done by an
1230 \typewithref{no.uio.ifi.refaktor.analyze.analyzers}{Analyzer}. If the
1231 preconditions validate, the upcoming changes are executed by an
1232 \typewithref{no.uio.ifi.refaktor.change.executors}{Executor}.
1234 \section{The Extract and Move Method Refactoring}
1235 %The Extract and Move Method Refactoring is implemented mainly using these
1238 % \item \type{ExtractAndMoveMethodChanger}
1239 % \item \type{ExtractAndMoveMethodPrefixesExtractor}
1240 % \item \type{Prefix}
1241 % \item \type{PrefixSet}
1244 \subsection{The Building Blocks}
1245 This is a composite refactoring, and hence is built up using several primitive
1246 refactorings. These basic building blocks are, as its name implies, the
1247 \ExtractMethod refactoring\citing{refactoring} and the \MoveMethod
1248 refactoring\citing{refactoring}. In Eclipse, the implementations of these
1249 refactorings are found in the classes
1250 \typewithref{org.eclipse.jdt.internal.corext.refactoring.code}{ExtractMethodRefactoring}
1252 \typewithref{org.eclipse.jdt.internal.corext.refactoring.structure}{MoveInstanceMethodProcessor},
1253 where the last class is designed to be used together with the processor-based
1254 \typewithref{org.eclipse.ltk.core.refactoring.participants}{MoveRefactoring}.
1256 \subsubsection{The ExtractMethodRefactoring Class}
1257 This class is quite simple in its use. The only parameters it requires for
1258 construction is a compilation
1259 unit\typeref{org.eclipse.jdt.core.ICompilationUnit}, the offset into the source
1260 code where the extraction shall start, and the length of the source to be
1261 extracted. Then you have to set the method name for the new method together with
1262 its visibility and some not so interesting parameters.
1264 \subsubsection{The MoveInstanceMethodProcessor Class}
1265 For the Move Method, the processor requires a little more advanced input than
1266 the class for the Extract Method. For construction it requires a method
1267 handle\typeref{org.eclipse.jdt.core.IMethod} for the method that is to be moved.
1268 Then the target for the move have to be supplied as the variable binding from a
1269 chosen variable declaration. In addition to this, one have to set some
1270 parameters regarding setters/getters, as well as delegation.
1272 To make a working refactoring from the processor, one have to create a
1273 \type{MoveRefactoring} with it.
1275 \subsection{The ExtractAndMoveMethodChanger Class}
1277 The \typewithref{no.uio.ifi.refaktor.changers}{ExtractAndMoveMethodChanger}
1278 class is a subclass of the class
1279 \typewithref{no.uio.ifi.refaktor.changers}{RefaktorChanger}. It is responsible
1280 for analyzing and finding the best target for, and also executing, a composition
1281 of the Extract Method and Move Method refactorings. This particular changer is
1282 the one of my changers that is closest to being a true LTK refactoring. It can
1283 be reworked to be one if the problems with overlapping changes are resolved. The
1284 changer requires a text selection and the name of the new method, or else a
1285 method name will be generated. The selection has to be of the type
1286 \typewithref{no.uio.ifi.refaktor.utils}{CompilationUnitTextSelection}. This
1287 class is a custom extension to
1288 \typewithref{org.eclipse.jface.text}{TextSelection}, that in addition to the
1289 basic offset, length and similar methods, also carry an instance of the
1290 underlying compilation unit handle for the selection.
1292 \subsubsection{The \type{ExtractAndMoveMethodAnalyzer}}
1293 The analysis and precondition checking is done by the
1294 \typewithref{no.uio.ifi.refaktor.analyze.analyzers}{ExtractAnd\-MoveMethodAnalyzer}.
1295 First is check whether the selection is a valid selection or not, with respect
1296 to statement boundaries and that it actually contains any selections. Then it
1297 checks the legality of both extracting the selection and also moving it to
1298 another class. If the selection is approved as legal, it is analyzed to find the
1299 presumably best target to move the extracted method to.
1301 For finding the best suitable target the analyzer is using a
1302 \typewithref{no.uio.ifi.refaktor.analyze.collectors}{PrefixesCollector} that
1303 collects all the possible candidates for the refactoring. All the non-candidates
1305 \typewithref{no.uio.ifi.refaktor.analyze.collectors}{UnfixesCollector} that
1306 collects all the targets that will give some kind of error if used. All prefixes
1307 (and unfixes) are represented by a
1308 \typewithref{no.uio.ifi.refaktor.extractors}{Prefix}, and they are collected
1309 into sets of prefixes. The safe prefixes is found by subtracting from the set of
1310 candidate prefixes the prefixes that is enclosing any of the unfixes. A prefix
1311 is enclosing an unfix if the unfix is in the set of its sub-prefixes. As an
1312 example, \texttt{``a.b''} is enclosing \texttt{``a''}, as is \texttt{``a''}. The
1313 safe prefixes is unified in a \type{PrefixSet}. If a prefix has only one
1314 occurrence, and is a simple expression, it is considered unsuitable as a move
1315 target. This occurs in statements such as \texttt{``a.foo()''}. For such
1316 statements it bares no meaning to extract and move them. It only generates an
1317 extra method and the calling of it.
1319 \todoin{Clean up sections/subsections.}
1321 \subsubsection{The \type{ExtractAndMoveMethodExecutor}}
1322 If the analysis finds a possible target for the composite refactoring, it is
1324 \typewithref{no.uio.ifi.refaktor.change.executors}{ExtractAndMoveMethodExecutor}.
1325 It is composed of the two executors known as
1326 \typewithref{no.uio.ifi.refaktor.change.executors}{ExtractMethodRefactoringExecutor}
1328 \typewithref{no.uio.ifi.refaktor.change.executors}{MoveMethodRefactoringExecutor}.
1329 The \type{ExtractAndMoveMethodExecutor} is responsible for gluing the two
1330 together by feeding the \type{MoveMethod\-RefactoringExecutor} with the
1331 resources needed after executing the extract method refactoring.
1332 \See{postExtractExecution}
1334 \subsubsection{The \type{ExtractMethodRefactoringExecutor}}
1335 This executor is responsible for creating and executing an instance of the
1336 \type{ExtractMethodRefactoring} class. It is also responsible for collecting
1337 some post execution resources that can be used to find the method handle for the
1338 extracted method, as well as information about its parameters, including the
1339 variable they originated from.
1341 \subsubsection{The \type{MoveMethodRefactoringExecutor}}
1342 This executor is responsible for creating and executing an instance of the
1343 \type{MoveRefactoring}. The move refactoring is a processor-based refactoring,
1344 and for the Move Method refactoring it is the \type{MoveInstanceMethodProcessor}
1347 The handle for the method to be moved is found on the basis of the information
1348 gathered after the execution of the Extract Method refactoring. The only
1349 information the \type{ExtractMethodRefactoring} is sharing after its execution,
1350 regarding find the method handle, is the textual representation of the new
1351 method signature. Therefore it must be parsed, the strings for types of the
1352 parameters must be found and translated to a form that can be used to look up
1353 the method handle from its type handle. They have to be on the unresolved
1354 form.\todo{Elaborate?} The name for the type is found from the original
1355 selection, since an extracted method must end up in the same type as the
1358 When analyzing a selection prior to performing the Extract Method refactoring, a
1359 target is chosen. It has to be a variable binding, so it is either a field or a
1360 local variable/parameter. If the target is a field, it can be used with the
1361 \type{MoveInstanceMethodProcessor} as it is, since the extracted method still is
1362 in its scope. But if the target is local to the originating method, the target
1363 that is to be used for the processor must be among its parameters. Thus the
1364 target must be found among the extracted method's parameters. This is done by
1365 finding the parameter information object that corresponds to the parameter that
1366 was declared on basis of the original target's variable when the method was
1367 extracted. (The extracted method must take one such parameter for each local
1368 variable that is declared outside the selection that is extracted.) To match the
1369 original target with the correct parameter information object, the key for the
1370 information object is compared to the key from the original target's binding.
1371 The source code must then be parsed to find the method declaration for the
1372 extracted method. The new target must be found by searching through the
1373 parameters of the declaration and choose the one that has the same type as the
1374 old binding from the parameter information object, as well as the same name that
1375 is provided by the parameter information object.
1378 \subsection{Finding the IMethod}\label{postExtractExecution}
1379 \todoin{Rename section. Write.}
1381 \subsection{Property collectors}
1382 The prefixes and unfixes are found by property
1383 collectors\typeref{no.uio.ifi.refaktor.extractors.collectors.PropertyCollector}.
1384 A property collector follows the visitor pattern\citing{designPatterns} and is
1385 of the \typewithref{org.eclipse.jdt.core.dom}{ASTVisitor} type. An
1386 \type{ASTVisitor} visits nodes in an abstract syntax tree that forms the Java
1387 document object model. The tree consists of nodes of type
1388 \typewithref{org.eclipse.jdt.core.do}{ASTNode}.
1390 \subsubsection{The PrefixesCollector}
1391 The \typewithref{no.uio.ifi.refaktor.extractors.collectors}{PrefixesCollector}
1392 finds prefixes that makes up tha basis for calculating move targets for the
1393 Extract and Move Method refactoring. It visits expression
1394 statements\typeref{org.eclipse.jdt.core.dom.ExpressionStatement} and creates
1395 prefixes from its expressions in the case of method invocations. The prefixes
1396 found is registered with a prefix set, together with all its sub-prefixes.
1397 \todo{Rewrite in the case of changes to the way prefixes are found}
1399 \subsubsection{The UnfixesCollector}\label{unfixes}
1400 The \typewithref{no.uio.ifi.refaktor.extractors.collectors}{UnfixesCollector}
1401 finds unfixes within a selection. That is prefixes that cannot be used as a
1402 basis for finding a move target in a refactoring.
1404 An unfix can be a name that is assigned to within a selection. The reason that
1405 this cannot be allowed, is that the result would be an assignment to the
1406 \type{this} keyword, which is not valid in Java \see{eclipse_bug_420726}.
1408 Prefixes that originates from variable declarations within the same selection
1409 are also considered unfixes. This is because when a method is moved, it needs to
1410 be called through a variable. If this variable is also within the method that is
1411 to be moved, this obviously cannot be done.
1413 Also considered as unfixes are variable references that are of types that is not
1414 suitable for moving a methods to. This can be either because it is not
1415 physically possible to move the method to the desired class or that it will
1416 cause compilation errors by doing so.
1418 If the type binding for a name is not resolved it is considered and unfix. The
1419 same applies to types that is only found in compiled code, so they have no
1420 underlying source that is accessible to us. (E.g. the \type{java.lang.String}
1423 Interfaces types are not suitable as targets. This is simply because interfaces
1424 in java cannot contain methods with bodies. (This thesis does not deal with
1425 features of Java versions later than Java 7. Java 8 has interfaces with default
1426 implementations of methods.) Neither are local types allowed. This accounts for
1427 both local and anonymous classes. Anonymous classes are effectively the same as
1428 interface types with respect to unfixes. Local classes could in theory be used
1429 as targets, but this is not possible due to limitations of the implementation of
1430 the Extract and Move Method refactoring. The problem is that the refactoring is
1431 done in two steps, so the intermediate state between the two refactorings would
1432 not be legal Java code. In the case of local classes, the problem is that, in
1433 the intermediate step, a selection referencing a local class would need to take
1434 the local class as a parameter if it were to be extracted to a new method. This
1435 new method would need to live in the scope of the declaring class of the
1436 originating method. The local class would then not be in the scope of the
1437 extracted method, thus bringing the source code into an illegal state. One could
1438 imagine that the method was extracted and moved in one operation, without an
1439 intermediate state. Then it would make sense to include variables with types of
1440 local classes in the set of legal targets, since the local classes would then be
1441 in the scopes of the method calls. If this makes any difference for software
1442 metrics that measure coupling would be a different discussion.
1445 \begin{multicols}{2}
1446 \begin{minted}[]{java}
1448 void declaresLocalClass() {
1463 \begin{minted}[]{java}
1464 // After Extract Method
1465 void declaresLocalClass() {
1476 // Intermediate step
1477 void fooBar(LocalClass inst) {
1483 \caption{When Extract and Move Method tries to use a variable with a local type
1484 as the move target, an intermediate step is taken that is not allowed. Here:
1485 \type{LocalClass} is not in the scope of \method{fooBar} in its intermediate
1487 \label{lst:extractMethod_LocalClass}
1490 The last class of names that are considered unfixes is names used in null tests.
1491 These are tests that reads like this: if \texttt{<name>} equals \var{null} then
1492 do something. If allowing variables used in those kinds of expressions as
1493 targets for moving methods, we would end up with code containing boolean
1494 expressions like \texttt{this == null}, which would not be meaningful, since
1495 \var{this} would never be \var{null}.
1497 \subsection{The Prefix Class}
1498 This class exists mainly for holding data about a prefix, such as the expression
1499 that the prefix represents and the occurrence count of the prefix within a
1500 selection. In addition to this, it has some functionality such as calculating
1501 its sub-prefixes and intersecting it with another prefix. The definition of the
1502 intersection between two prefixes is a prefix representing the longest common
1503 expression between the two.
1505 \subsection{The PrefixSet Class}
1506 A prefix set holds elements of type \type{Prefix}. It is implemented with the
1507 help of a \typewithref{java.util}{HashMap} and contains some typical set
1508 operations, but it does not implement the \typewithref{java.util}{Set}
1509 interface, since the prefix set does not need all of the functionality a
1510 \type{Set} requires to be implemented. In addition It needs some other
1511 functionality not found in the \type{Set} interface. So due to the relatively
1512 limited use of prefix sets, and that it almost always needs to be referenced as
1513 such, and not a \type{Set<Prefix>}, it remains as an ad hoc solution to a
1516 There are two ways adding prefixes to a \type{PrefixSet}. The first is through
1517 its \method{add} method. This works like one would expect from a set. It adds
1518 the prefix to the set if it does not already contain the prefix. The other way
1519 is to \emph{register} the prefix with the set. When registering a prefix, if the
1520 set does not contain the prefix, it is just added. If the set contains the
1521 prefix, its count gets incremented. This is how the occurrence count is handled.
1523 The prefix set also computes the set of prefixes that is not enclosing any
1524 prefixes of another set. This is kind of a set difference operation only for
1527 \subsection{Hacking the Refactoring Undo
1528 History}\label{hacking_undo_history}
1529 \todoin{Where to put this section?}
1531 As an attempt to make multiple subsequent changes to the workspace appear as a
1532 single action (i.e. make the undo changes appear as such), I tried to alter
1533 the undo changes\typeref{org.eclipse.ltk.core.refactoring.Change} in the history
1534 of the refactorings.
1536 My first impulse was to remove the, in this case, last two undo changes from the
1537 undo manager\typeref{org.eclipse.ltk.core.refactoring.IUndoManager} for the
1538 Eclipse refactorings, and then add them to a composite
1539 change\typeref{org.eclipse.ltk.core.refactoring.CompositeChange} that could be
1540 added back to the manager. The interface of the undo manager does not offer a
1541 way to remove/pop the last added undo change, so a possible solution could be to
1542 decorate\citing{designPatterns} the undo manager, to intercept and collect the
1543 undo changes before delegating to the \method{addUndo}
1544 method\methodref{org.eclipse.ltk.core.refactoring.IUndoManager}{addUndo} of the
1545 manager. Instead of giving it the intended undo change, a null change could be
1546 given to prevent it from making any changes if run. Then one could let the
1547 collected undo changes form a composite change to be added to the manager.
1549 There is a technical challenge with this approach, and it relates to the undo
1550 manager, and the concrete implementation
1551 UndoManager2\typeref{org.eclipse.ltk.internal.core.refactoring.UndoManager2}.
1552 This implementation is designed in a way that it is not possible to just add an
1553 undo change, you have to do it in the context of an active
1554 operation\typeref{org.eclipse.core.commands.operations.TriggeredOperations}.
1555 One could imagine that it might be possible to trick the undo manager into
1556 believing that you are doing a real change, by executing a refactoring that is
1557 returning a kind of null change that is returning our composite change of undo
1558 refactorings when it is performed.
1560 Apart from the technical problems with this solution, there is a functional
1561 problem: If it all had worked out as planned, this would leave the undo history
1562 in a dirty state, with multiple empty undo operations corresponding to each of
1563 the sequentially executed refactoring operations, followed by a composite undo
1564 change corresponding to an empty change of the workspace for rounding of our
1565 composite refactoring. The solution to this particular problem could be to
1566 intercept the registration of the intermediate changes in the undo manager, and
1567 only register the last empty change.
1569 Unfortunately, not everything works as desired with this solution. The grouping
1570 of the undo changes into the composite change does not make the undo operation
1571 appear as an atomic operation. The undo operation is still split up into
1572 separate undo actions, corresponding to the change done by its originating
1573 refactoring. And in addition, the undo actions has to be performed separate in
1574 all the editors involved. This makes it no solution at all, but a step toward
1577 There might be a solution to this problem, but it remains to be found. The
1578 design of the refactoring undo management is partly to be blamed for this, as it
1579 it is to complex to be easily manipulated.
1584 \chapter{Analyzing Source Code in Eclipse}
1585 Eclipse is following the common paradigm of using an abstract syntaxt tree for
1586 source code analysis and manipulation.
1588 \section{The Abstract Synax Tree}
1589 When parsing program source code into something that can be used as a foundation
1590 for analysis, the start of the process follows the same steps as in a compiler.
1591 This is all natural, because the way a compiler anayzes code is no different
1592 from how source manipulation programs would do it, except for some properties of
1593 code that is analyzed in the parser, and that they may be differing in what
1594 kinds of properties they analyze. Thus the process of translation source code
1595 into a structure that is suitable for analyzing, can be seen as a kind of
1596 interrupted compilation process.
1598 The process starts with a \emph{scanner}, or lexer. The job of the scanner is to
1599 read the source code and divide it into tokens for the parser. Therefore, it is
1600 also sometimes called a tokenizer. A token is a logical unit, defined in the
1601 language specification, consisting of one or more consecutive characters. In
1602 the java language the tokens can for instance be the \var{this} keyword, a curly
1603 bracket \var{\{} or a \var{nameToken}. It is recognized by the scanner on the
1604 basis of something eqivalent of a regular expression. This part of the process
1605 is often implemented with the use of a finite automata. In fact, it is common to
1606 specify the tokens in regular expressions, that in turn is translated into a
1607 finite automata lexer. This process can be automated.
1609 The program component used to translate a a stream of tokens into something
1610 meaningful, is called a parser. A parser is fed tokens from the scanner and
1611 performs an analysis of the structure of a program. It verifies that the syntax
1612 is correct according to the grammar rules of a language, that is usually
1613 specified in a context-free grammar, and often in a variant of the
1615 Form}\footnote{\url{https://en.wikipedia.org/wiki/Backus-Naur\_Form}}. The
1616 result coming from the parser is in the form of an \emph{Abstract Syntax Tree},
1617 AST for short. It is called \emph{abstract}, because the structure does not
1618 contain all of the tokens produced by the scanner. It only contain logical
1619 constructs, and because it forms a tree, all kinds of parentheses and brackets
1620 are implicit in the structure. It is this AST that is used when performing the
1621 semantic analysis of the code.
1623 As an example we can think of the expression \code{(5 + 7) * 2}. The root of
1624 this tree would in Eclipse be an \type{InfixExpression} with the operator
1625 \var{TIMES}, and a left operand that is also an \type{InfixExpression} with the
1626 operator \var{PLUS}. The left operand \type{InfixExpression}, has in turn a left
1627 operand of type \type{NumberLiteral} with the value \var{``5''} and a right
1628 operand \type{NumberLiteral} with the value \var{``7''}. The root will have a
1629 right operand of type \type{NumberLiteral} and value \var{``2''}. The AST for
1630 this expression is illustrated in \myref{fig:astInfixExpression}.
1634 \begin{tikzpicture}[scale=0.7]
1635 \tikzset{level distance=40pt}
1636 \tikzset{edge from parent/.append style={thick}}
1637 \tikzset{every internal node/.style={ellipse,draw,fill=lightgray}}
1638 \tikzset{every leaf node/.style={draw=none,fill=none}}
1640 \Tree [.\type{InfixExpression} [.\type{InfixExpression}
1641 [.\type{NumberLiteral} \var{``5''} ] [.\type{Operator} \var{PLUS} ]
1642 [.\type{NumberLiteral} \var{``7''} ] ]
1643 [.\type{Operator} \var{TIMES} ]
1644 [.\type{NumberLiteral} \var{``2''} ]
1647 \caption{The abstract syntax tree for the expression \code{(5 + 7) * 2}.}
1648 \label{fig:astInfixExpression}
1651 \subsection{The AST in Eclipse}
1652 In Eclipse, every node in the AST is a child of the abstract superclass
1653 \typewithref{org.eclipse.jdt.core.dom}{ASTNode}. Every \type{ASTNode}, among a
1654 lot of other things, provides information about its position and length in the
1655 source code, as well as a reference to its parent and to the root of the tree.
1657 The root of the AST is always of type \type{CompilationUnit}. It is not the same
1658 as an instance of an \type{ICompilationUnit}, which is the compilation unit
1659 handle of the Java model. The children of a \type{CompilationUnit} is an
1660 optional \type{PackageDeclaration}, zero or more nodes of type
1661 \type{ImportDecaration} and all its top-level type declarations that has node
1662 types \type{AbstractTypeDeclaration}.
1664 An \type{AbstractType\-Declaration} can be one of the types
1665 \type{AnnotationType\-Declaration}, \type{Enum\-Declaration} or
1666 \type{Type\-Declaration}. The children of an \type{AbstractType\-Declaration}
1667 must be a subtype of a \type{BodyDeclaration}. These subtypes are:
1668 \type{AnnotationTypeMember\-Declaration}, \type{EnumConstant\-Declaration},
1669 \type{Field\-Declaration}, \type{Initializer} and \type{Method\-Declaration}.
1671 Of the body declarations, the \type{Method\-Declaration} is the most interesting
1672 one. Its children include lists of modifiers, type parameters, parameters and
1673 exceptions. It has a return type node and a body node. The body, if present, is
1674 of type \type{Block}. A \type{Block} is itself a \type{Statement}, and its
1675 children is a list of \type{Statement} nodes.
1677 There are too many types of the abstract type \type{Statement} to list up, but
1678 there exists a subtype of \type{Statement} for every statement type of Java, as
1679 one would expect. This also applies to the abstract type \type{Expression}.
1680 However, the expression \type{Name} is a little special, since it is both used
1681 as an operand in compound expressions, as well as for names in type declarations
1684 \section{The Java model}
1687 \begin{tikzpicture}[%
1688 grow via three points={one child at (0,-0.7) and
1689 two children at (0,-0.7) and (0,-1.4)},
1690 edge from parent path={(\tikzparentnode.south west)+(0.5,0) |-
1691 (\tikzchildnode.west)}]
1692 \tikzstyle{every node}=[draw=black,thick,anchor=west]
1693 \tikzstyle{selected}=[draw=red,fill=red!30]
1694 \tikzstyle{optional}=[dashed,fill=gray!50]
1695 \node {\type{IJavaProject}}
1696 child { node {\type{IPackageFragmentRoot}}
1697 child { node {\type{IPackageFragment}}
1698 child { node {\type{ICompilationUnit}}
1699 child { node {\type{IType}}
1700 child { node {\type{\{ IType \}*}}
1701 child { node {\type{\ldots}}}
1704 child { node {\type{\{ IField \}*}}}
1705 child { node {\type{IMethod}}
1706 child { node {\type{\{ IType \}*}}
1707 child { node {\type{\ldots}}}
1712 child { node {\type{\{ IMethod \}*}}}
1721 child { node {\type{\{ IType \}*}}}
1732 child { node {\type{\{ ICompilationUnit \}*}}}
1745 child { node {\type{\{ IPackageFragment \}*}}}
1760 child { node {\type{\{ IPackageFragmentRoot \}*}}}
1763 \caption{The Java model. ``\type{\{ SomeElement \}*}'' means
1764 \type{SomeElement} zero or more times. ``\type{\ldots}'' is used for recursive
1766 \label{fig:javaModel}
1770 \section{Illegal selections}
1772 \subsection{Not all branches end in return}
1774 \subsection{Ambiguous return statement}
1775 This problem occurs when there is either more than one assignment to a local
1776 variable that is used outside of the selection, or there is only one, but there
1777 are also return statements in the selection.
1779 \todoin{Explain why we do not need to consider variables assigned inside
1780 local/anonymous classes. (The referenced variables need to be final and so
1783 \chapter{Eclipse Bugs Found}
1784 \todoin{Add other things and change headline?}
1786 \section{Eclipse bug 420726: Code is broken when moving a method that is
1787 assigning to the parameter that is also the move
1788 destination}\label{eclipse_bug_420726}
1789 This bug\footnote{\url{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=420726}}
1790 was found when analyzing what kinds of names that was to be considered as
1791 \emph{unfixes} \see{unfixes}.
1793 \subsection{The bug}
1794 The bug emerges when trying to move a method from one class to another, and when
1795 the target for the move (must be a variable, local or field) is both a parameter
1796 variable and also is assigned to within the method body. Eclipse allows this to
1797 happen, although it is the sure path to a compilation error. This is because we
1798 would then have an assignment to a \var{this} expression, which is not allowed
1801 \subsection{The solution}
1802 The solution to this problem is to add all simple names that are assigned to in
1803 a method body to the set of unfixes.
1805 \section{Eclipse bug 429416: IAE when moving method from anonymous class}
1807 discovered\footnote{\url{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=429416}}
1808 this bug during a batch change on the \type{org.eclipse.jdt.ui} project.
1810 \subsection{The bug}
1811 This bug surfaces when trying to use the Move Method refactoring to move a
1812 method from an anonymous class to another class. This happens both for my
1813 simulation as well as in Eclipse, through the user interface. It only occurs
1814 when Eclipse analyzes the program and finds it necessary to pass an instance of
1815 the originating class as a parameter to the moved method. I.e. it want to pass a
1816 \var{this} expression. The execution ends in an
1817 \typewithref{java.lang}{IllegalArgumentException} in
1818 \typewithref{org.eclipse.jdt.core.dom}{SimpleName} and its
1819 \method{setIdentifier(String)} method. The simple name is attempted created in
1821 \methodwithref{org.eclipse.jdt.internal.corext.refactoring.structure.\\MoveInstanceMethodProcessor}{createInlinedMethodInvocation}
1822 so the \type{MoveInstanceMethodProcessor} was early a clear suspect.
1824 The \method{createInlinedMethodInvocation} is the method that creates a method
1825 invocation where the previous invocation to the method that was moved was. From
1826 its code it can be read that when a \var{this} expression is going to be passed
1827 in to the invocation, it shall be qualified with the name of the original
1828 method's declaring class, if the declaring class is either an anonymous clas or
1829 a member class. The problem with this, is that an anonymous class does not have
1830 a name, hence the term \emph{anonymous} class! Therefore, when its name, an
1831 empty string, is passed into
1832 \methodwithref{org.eclipse.jdt.core.dom.AST}{newSimpleName} it all ends in an
1833 \type{IllegalArgumentException}.
1835 \subsection{How I solved the problem}
1836 Since the \type{MoveInstanceMethodProcessor} is instantiated in the
1837 \typewithref{no.uio.ifi.refaktor.change.executors}{MoveMethod\-RefactoringExecutor},
1838 and only need to be a
1839 \typewithref{org.eclipse.ltk.core.refactoring.participants}{MoveProcessor}, I
1840 was able to copy the code for the original move processor and modify it so that
1841 it works better for me. It is now called
1842 \typewithref{no.uio.ifi.refaktor.refactorings.processors}{ModifiedMoveInstanceMethodProcessor}.
1843 The only modification done (in addition to some imports and suppression of
1844 warnings), is in the \method{createInlinedMethodInvocation}. When the declaring
1845 class of the method to move is anonymous, the \var{this} expression in the
1846 parameter list is not qualified with the declaring class' (empty) name.
1848 \section{Eclipse bug 429954: Extracting statement with reference to local type
1849 breaks code}\label{eclipse_bug_429954}
1850 The bug\footnote{\url{https://bugs.eclipse.org/bugs/show\_bug.cgi?id=429954}}
1851 was discovered when doing some changes to the way unfixes is computed.
1853 \subsection{The bug}
1854 The problem is that Eclipse is allowing selections that references variables of
1855 local types to be extracted. When this happens the code is broken, since the
1856 extracted method must take a parameter of a local type that is not in the
1857 methods scope. The problem is illustrated in
1858 \myref{lst:extractMethod_LocalClass}, but there in another setting.
1860 \subsection{Actions taken}
1861 There are no actions directly springing out of this bug, since the Extract
1862 Method refactoring cannot be meant to be this way. This is handled on the
1863 analysis stage of our Extract and Move Method refactoring. So names representing
1864 variables of local types is considered unfixes \see{unfixes}.
1865 \todoin{write more when fixing this in legal statements checker}
1867 \chapter{Related Work}
1869 \section{The compositional paradigm of refactoring}
1870 This paradigm builds upon the observation of Vakilian et
1871 al.\citing{vakilian2012}, that of the many automated refactorings existing in
1872 modern IDEs, the simplest ones are dominating the usage statistics. The report
1873 mainly focuses on \emph{Eclipse} as the tool under investigation.
1875 The paradigm is described almost as the opposite of automated composition of
1876 refactorings \see{compositeRefactorings}. It works by providing the programmer
1877 with easily accessible primitive refactorings. These refactorings shall be
1878 accessed via keyboard shortcuts or quick-assist menus\footnote{Think
1879 quick-assist with Ctrl+1 in Eclipse} and be promptly executed, opposed to in the
1880 currently dominating wizard-based refactoring paradigm. They are ment to
1881 stimulate composing smaller refactorings into more complex changes, rather than
1882 doing a large upfront configuration of a wizard-based refactoring, before
1883 previewing and executing it. The compositional paradigm of refactoring is
1884 supposed to give control back to the programmer, by supporting \himher with an
1885 option of performing small rapid changes instead of large changes with a lesser
1886 degree of control. The report authors hope this will lead to fewer unsuccessful
1887 refactorings. It also could lower the bar for understanding the steps of a
1888 larger composite refactoring and thus also help in figuring out what goes wrong
1889 if one should choose to op in on a wizard-based refactoring.
1891 Vakilian and his associates have performed a survey of the effectiveness of the
1892 compositional paradigm versus the wizard-based one. They claim to have found
1893 evidence of that the \emph{compositional paradigm} outperforms the
1894 \emph{wizard-based}. It does so by reducing automation, which seem
1895 counterintuitive. Therefore they ask the question ``What is an appropriate level
1896 of automation?'', and thus questions what they feel is a rush toward more
1897 automation in the software engineering community.