]> git.uio.no Git - ifi-stolz-refaktor.git/blob - thesis/master-thesis-erlenkr.tex
65618d6ce09a12380e359f7c00981e90145a9978
[ifi-stolz-refaktor.git] / thesis / master-thesis-erlenkr.tex
1 \documentclass[USenglish]{ifimaster}
2 \usepackage{import}
3 \usepackage[utf8]{inputenc}
4 \usepackage[T1]{fontenc,url}
5 \usepackage{lmodern} % using Latin Modern to be able to use bold typewriter font
6 \urlstyle{sf}
7 \usepackage{babel,textcomp,csquotes,ifimasterforside,varioref,graphicx}
8 \usepackage[hidelinks]{hyperref}
9 \usepackage[style=numeric-comp,backend=bibtex]{biblatex}
10 \usepackage{amsthm}
11 \usepackage{todonotes}
12 \usepackage{xspace}
13 \usepackage{he-she}
14 \usepackage{verbatim}
15 \usepackage{minted}
16 \usemintedstyle{bw}
17 \usepackage{perpage} %the perpage package
18 \MakePerPage{footnote} %the perpage package command
19
20 \theoremstyle{definition}
21 \newtheorem*{wordDef}{Definition}
22
23 \graphicspath{ {./figures/} }
24
25 \newcommand{\definition}[1]{\begin{wordDef}#1\end{wordDef}}
26 \newcommand{\see}[1]{(see section \ref{#1})}
27 \newcommand{\See}[1]{(See section \ref{#1}.)}
28 \newcommand{\explanation}[3]{\noindent\textbf{\textit{#1}}\\*\emph{When:} 
29 #2\\*\emph{How:} #3\\*[-7px]}
30
31 \newcommand{\type}[1]{\texttt{\textbf{#1}}}
32 \newcommand{\typeref}[1]{\footnote{\type{#1}}}
33 \newcommand{\typewithref}[2]{\type{#2}\typeref{#1.#2}}
34 \newcommand{\method}[1]{\type{#1}}
35 \newcommand{\methodref}[2]{\footnote{\type{#1}\method{\##2()}}}
36 \newcommand{\methodwithref}[2]{\method{#2}\footnote{\type{#1}\method{\##2()}}}
37 \newcommand{\var}[1]{\type{#1}}
38
39 \newcommand{\refactoring}[1]{\emph{#1}}
40 \newcommand{\ExtractMethod}{\refactoring{Extract Method}\xspace}
41 \newcommand{\MoveMethod}{\refactoring{Move Method}\xspace}
42
43 \newcommand{\citing}[1]{~\cite{#1}}
44
45 \newcommand\todoin[2][]{\todo[inline, caption={2do}, #1]{
46 \begin{minipage}{\textwidth-4pt}#2\end{minipage}}}
47
48 \title{Refactoring}
49 \subtitle{An unfinished essay}
50 \author{Erlend Kristiansen}
51
52 \bibliography{bibliography/master-thesis-erlenkr-bibliography}
53
54 \begin{document}
55 \ififorside
56 \frontmatter{}
57
58
59 \chapter*{Abstract}
60 \todoin{\textbf{Remove all todos (including list) before delivery/printing!!!}}
61 \todoin{Write abstract}
62
63 \tableofcontents{}
64 \listoffigures{}
65 \listoftables{}
66
67 \chapter*{Preface}
68
69 The discussions in this report must be seen in the context of object oriented 
70 programming languages, and Java in particular, since that is the language in 
71 which most of the examples will be given. All though the techniques discussed 
72 may be applicable to languages from other paradigms, they will not be the 
73 subject of this report.
74
75 \mainmatter
76
77 \chapter{What is Refactoring?}
78
79 This question is best answered by first defining the concept of a 
80 \emph{refactoring}, what it is to \emph{refactor}, and then discuss what aspects 
81 of programming that make people want to refactor their code.
82
83 \section{Defining refactoring}
84 Martin Fowler, in his masterpiece on refactoring \cite{refactoring}, defines a 
85 refactoring like this:
86
87 \begin{quote}
88   \emph{Refactoring} (noun): a change made to the \todo{what does he mean by 
89   internal?} internal structure of software to make it easier to understand and 
90   cheaper to modify without changing its observable 
91   behavior.~\cite[p.~53]{refactoring}
92 \end{quote}
93
94 \noindent This definition assign additional meaning to the word 
95 \emph{refactoring}, beyond the composition of the prefix \emph{re-}, usually 
96 meaning something like ``again'' or ``anew'', and the word \emph{factoring}, 
97 that can mean to isolate the \emph{factors} of something. Here a \emph{factor} 
98 would be close to the mathematical definition of something that divides a 
99 quantity, without leaving a remainder. Fowler is mixing the \emph{motivation} 
100 behind refactoring into his definition.  Instead it could be made clean, only 
101 considering the mechanical and behavioral aspects of refactoring. That is to 
102 factor the program again, putting it together in a different way than before, 
103 while preserving the behavior of the program. An alternative definition could 
104 then be: 
105
106 \definition{A \emph{refactoring} is a transformation
107 done to a program without altering its external behavior.}
108
109 From this we can conclude that a refactoring primarily changes how the 
110 \emph{code} of a program is perceived by the \emph{programmer}, and not the 
111 \emph{behavior} experienced by any user of the program. Although the logical 
112 meaning is preserved, such changes could potentially alter the program's 
113 behavior when it comes to performance gain or -penalties. So any logic depending 
114 on the performance of a program could make the program behave differently after 
115 a refactoring.
116
117 In the extreme case one could argue that such a thing as \emph{software 
118 obfuscation} is to refactor. If we where to define it as a refactoring, it could 
119 be defined as a composite refactoring \see{compositeRefactorings}, consisting 
120 of, for instance, a series of rename refactorings. (But it could of course be 
121 much more complex, and the mechanics of it would not exactly be carved in 
122 stone.) To perform some serious obfuscation one would also take advantage of 
123 techniques not found among established refactorings, such as removing 
124 whitespace. This might not even generate a different syntax tree for languages 
125 not sensitive to whitespace, placing it in the gray area of what kind of 
126 transformations is to be considered refactorings.
127
128 Finally, to \emph{refactor} is (quoting Martin Fowler)
129 \begin{quote}
130   \ldots to restructure software by applying a series of refactorings without 
131   changing its observable behavior.~\cite[p.~54]{refactoring}
132 \end{quote}
133
134 \section{The etymology of 'refactoring'}
135 It is a little difficult to pinpoint the exact origin of the word 
136 ``refactoring'', as it seems to have evolved as part of a colloquial 
137 terminology, more than a scientific term. There is no authoritative source for a 
138 formal definition of it. 
139
140 According to Martin Fowler\citing{etymology-refactoring}, there may also be more 
141 than one origin of the word. The most well-known source, when it comes to the 
142 origin of \emph{refactoring}, is the Smalltalk\footnote{\emph{Smalltalk}, 
143 object-oriented, dynamically typed, reflective programming language.}\todo{find 
144 reference to Smalltalk website or similar?} community and their infamous 
145 \emph{Refactoring 
146 Browser}\footnote{\url{http://st-www.cs.illinois.edu/users/brant/Refactory/RefactoringBrowser.html}} 
147 described in the article \emph{A Refactoring Tool for 
148 Smalltalk}\citing{refactoringBrowser1997}, published in 1997.  
149 Allegedly\citing{etymology-refactoring}, the metaphor of factoring programs was 
150 also present in the Forth\footnote{\emph{Forth} -- stack-based, extensible 
151 programming language, without type-checking. See \url{http://www.forth.org}} 
152 community, and the word ``refactoring'' is mentioned in a book by Leo Brodie, 
153 called \emph{Thinking Forth}\citing{brodie1984}, first published in 
154 1984\footnote{\emph{Thinking Forth} was first published in 1984 by the 
155 \emph{Forth Interest Group}.  Then it was reprinted in 1994 with minor 
156 typographical corrections, before it was transcribed into an electronic edition 
157 typeset in \LaTeX\ and published under a Creative Commons licence in 2004. The 
158 edition cited here is the 2004 edition, but the content should essentially be as 
159 in 1984.}. The exact word is only printed one place\footnote{p. 232}, but the 
160 term \emph{factoring} is prominent in the book, that also contains a whole 
161 chapter dedicated to (re)factoring, and how to keep the (Forth) code clean and 
162 maintainable.
163
164 \begin{quote}
165   \ldots good factoring technique is perhaps the most important skill for a 
166   Forth programmer.~\cite[p.~172]{brodie1984}
167 \end{quote}
168
169 \noindent Brodie also express what \emph{factoring} means to him:
170
171 \begin{quote}
172   Factoring means organizing code into useful fragments. To make a fragment 
173   useful, you often must separate reusable parts from non-reusable parts. The  
174   reusable parts become new definitions. The non-reusable parts become arguments 
175   or parameters to the definitions.~\cite[p.~172]{brodie1984}
176 \end{quote}
177
178 Fowler claims that the usage of the word \emph{refactoring} did not pass between 
179 the \emph{Forth} and \emph{Smalltalk} communities, but that it emerged 
180 independently in each of the communities.
181
182 \todoin{more history?}
183
184 \section{Motivation -- Why people refactor}
185 To get a grasp of what refactoring is all about, we can try to answer this 
186 question: \emph{Why do people refactor?} Possible answers could include: ``To 
187 remove duplication'' or ``to break up long methods''.  Practitioners of the art 
188 of Design Patterns\citing{designPatterns} could say that they do it to introduce 
189 a long-needed pattern into their program's design.  So it is safe to say that 
190 peoples' intentions are to make their programs \emph{better} in some sense. But 
191 what aspects of the programs are becoming improved?
192
193 As already mentioned, people often refactor to get rid of duplication. Moving 
194 identical or similar code into methods, and maybe pushing those up or down in 
195 their class hierarchies. Making template methods for overlapping 
196 algorithms/functionality and so on.  It's all about gathering what belongs 
197 together and putting it all in one place.  And the result? The code is easier to 
198 maintain. When removing the implicit coupling between the code snippets, the 
199 location of a bug is limited to only one place, and new functionality need only 
200 to be added this one place, instead of a number of places people might not even 
201 remember.
202
203 The same people find out that their program contains a lot of long and 
204 hard-to-grasp methods. Then what do they do? They begin dividing their methods 
205 into smaller ones, using the \ExtractMethod 
206 refactoring\citing{refactoring}.  Then they may discover something about their 
207 program that they weren't aware of before; revealing bugs they didn't know about 
208 or couldn't find due to the complex structure of their program. \todo{Proof?} 
209 Making the methods smaller and giving good names to the new ones clarifies the 
210 algorithms and enhances the \emph{understandability} of the program 
211 \see{magic_number_seven}. This makes simple refactoring an excellent method for 
212 exploring unknown program code, or code that you had forgotten that you wrote!
213
214 The word \emph{simple} came up in the last section. In fact, most primitive 
215 refactorings are simple. The true power of them are revealed first when they are 
216 combined into larger --- higher level --- refactorings, called \emph{composite 
217 refactorings} \see{compositeRefactorings}. Often the goal of such a series of 
218 refactorings is a design pattern. Thus the \emph{design} can be evolved 
219 throughout the lifetime of a program, opposed to designing up-front.  It's all 
220 about being structured and taking small steps to improve a program's design.
221
222 Many refactorings are aimed at lowering the coupling between different classes 
223 and different layers of logic. \todo{which refactorings?} Say for instance that 
224 the coupling between the user interface and the business logic of a program is 
225 lowered.  Then the business logic of the program could much easier be the target 
226 of automated tests, increasing the productivity in the software development 
227 process. It is also easier to distribute (e.g. between computers) the different 
228 components of a program if they are sufficiently decoupled.
229
230 Another effect of refactoring is that with the increased separation of concerns 
231 coming out of many refactorings, the \emph{performance} is improved.  When 
232 profiling programs, the problem parts are narrowed down to smaller parts of the 
233 code, which are easier to tune, and optimization can be performed only where 
234 needed and in a more effective way.
235
236 Last, but not least, and this should probably be the best reason to refactor, is 
237 to refactor to \emph{facilitate a program change}. If one has managed to keep 
238 one's code clean and tidy, and the code is not bloated with design patterns that 
239 is not ever going to be needed, then some refactoring might be needed to 
240 introduce a design pattern that is appropriate for the change that is going to 
241 happen.
242
243 Refactoring program code --- with a goal in mind --- can give the code itself 
244 more value. That is in the form of robustness to bugs, understandability and 
245 maintainability. With the first as an obvious advantage, but with the following 
246 two being also very important for software development. By incorporating 
247 refactoring in the development process, bugs are found faster, new functionality 
248 is added more easily and code is easier to understand by the next person exposed 
249 to it, which might as well be the person who wrote it. The consequence of this, 
250 is that refactoring can increase the average productivity of the development 
251 process, and thus also add to the monetary value of a business in the long run.  
252 Where this last point also should open the eyes of some nearsighted managers who 
253 seldom see beyond the next milestone.
254
255 \section{The magical number seven}\label{magic_number_seven}
256 \emph{The magical number seven, plus or minus two: some limits on our capacity 
257 for processing information}\citing{miller1956} is an article by George A. Miller 
258 that was published in the journal \emph{Psychological Review} in 1956. It 
259 presents evidence that support that the capacity of the number of objects a 
260 human being can hold in its working memory is roughly seven, plus or minus two 
261 objects. This number varies a bit depending on the nature and complexity of the 
262 objects, but is according to Miller ``\ldots never changing so much as to be 
263 unrecognizable.''
264
265 Miller's article culminates in the section called \emph{Recoding}, a term he 
266 borrows from communication theory. The central result in this section is that by 
267 recoding information, the capacity of the amount of information that a human can 
268 process at a time is increased. By \emph{recoding}, Miller means to group 
269 objects together in chunks and give each chunk a new name that it can be 
270 remembered by. By organizing objects into patterns of ever growing depth, one 
271 can memorize and process a much larger amount of data than if it were to be 
272 represented as its basic pieces. This grouping and renaming is analogous to how 
273 many refactorings work, by grouping pieces of code and give them a new name.  
274 Examples are the central \ExtractMethod and \refactoring{Extract Class} 
275 refactorings\citing{refactoring}.
276
277 \begin{quote}
278   \ldots recoding is an extremely powerful weapon for increasing the amount of 
279   information that we can deal with.~\cite[p.~95]{miller1956}
280 \end{quote}
281
282 An example from the article address the problem of memorizing a sequence of 
283 binary digits. Let us say we have the following sequence\footnote{The example 
284   presented here is slightly modified (and shortened) from what is presented in 
285   the original article\citing{miller1956}, but it is essentially the same.} of 
286 16 binary digits: ``1010001001110011''. Most of us will have a hard time 
287 memorizing this sequence by only reading it once or twice. Imagine if we instead 
288 translate it to this sequence: ``A273''. If you have a background from computer 
289 science, it will be obvious that the latest sequence is the first sequence 
290 recoded to be represented by digits with base 16. Most people should be able to 
291 memorize this last sequence by only looking at it once.
292
293 Another result from the Miller article is that when the amount of information a 
294 human must interpret increases, it is crucial that the translation from one code 
295 to another must be almost automatic for the subject to be able to remember the 
296 translation, before \heshe is presented with new information to recode.  Thus 
297 learning and understanding how to best organize certain kinds of data is 
298 essential to efficiently handle that kind of data in the future. This is much 
299 like when children learn to read. First they must learn how to recognize 
300 letters. Then they can learn distinct words, and later read sequences of words 
301 that form whole sentences. Eventually, most of them will be able to read whole 
302 books and briefly retell the important parts of its content. This suggest that 
303 the use of design patterns\citing{designPatterns} is a good idea when reasoning 
304 about computer programs. With extensive use of design patterns when creating 
305 complex program structures, one does not always have to read whole classes of 
306 code to comprehend how they function, it may be sufficient to only see the name 
307 of a class to almost fully understand its responsibilities.
308
309 \begin{quote}
310   Our language is tremendously useful for repackaging material into a few chunks 
311   rich in information.~\cite[p.~95]{miller1956}
312 \end{quote}
313
314 Without further evidence, these results at least indicates that refactoring 
315 source code into smaller units with higher cohesion and, when needed, 
316 introducing appropriate design patterns, should aid in the cause of creating 
317 computer programs that are easier to maintain and has code that is easier (and 
318 better) understood.
319
320 \section{Notable contributions to the refactoring literature}
321 \todoin{Update with more contributions}
322
323 \begin{description}
324   \item[1992] William F. Opdyke submits his doctoral dissertation called 
325     \emph{Refactoring Object-Oriented Frameworks}\citing{opdyke1992}. This 
326     work defines a set of refactorings, that are behavior preserving given that 
327     their preconditions are met. The dissertation is focused on the automation 
328     of refactorings.
329   \item[1999] Martin Fowler et al.: \emph{Refactoring: Improving the Design of 
330     Existing Code}\citing{refactoring}. This is maybe the most influential text 
331     on refactoring. It bares similarities with Opdykes thesis\citing{opdyke1992} 
332     in the way that it provides a catalog of refactorings. But Fowler's book is 
333     more about the craft of refactoring, as he focuses on establishing a 
334     vocabulary for refactoring, together with the mechanics of different 
335     refactorings and when to perform them. His methodology is also founded on 
336   the principles of test-driven development.
337   \item[2005] Joshua Kerievsky: \emph{Refactoring to 
338     Patterns}\citing{kerievsky2005}. This book is heavily influenced by Fowler's 
339     \emph{Refactoring}\citing{refactoring} and the Gang of Four \emph{Design 
340     Patterns}\citing{designPatterns}. It is building on the refactoring 
341     catalogue from Fowler's book, but is trying to bridge the gap between 
342     \emph{refactoring} and \emph{design patterns} by providing a series of 
343     higher-level composite refactorings, that makes code evolve toward or away 
344     from certain design patterns. The book is trying to build up the readers 
345     intuition around \emph{why} one would want to use a particular design 
346     pattern, and not just \emph{how}. The book is encouraging evolutionary 
347     design.  \See{relationToDesignPatterns}
348 \end{description}
349
350 \section{Tool support}\label{toolSupport}
351
352 \subsection{Tool support for Java}
353 This section will briefly compare the refatoring support of the three IDEs 
354 \emph{Eclipse}\footnote{\url{http://www.eclipse.org/}}, \emph{IntelliJ 
355 IDEA}\footnote{The IDE under comparison is the \emph{Community Edition}, 
356 \url{http://www.jetbrains.com/idea/}} and 
357 \emph{NetBeans}\footnote{\url{https://netbeans.org/}}. These are the most 
358 popular Java IDEs\citing{javaReport2011}.
359
360 All three IDEs provide support for the most useful refactorings, like the 
361 different extract, move and rename refactorings. In fact, Java-targeted IDEs are 
362 known for their good refactoring support, so this did not appear as a big 
363 surprise.
364
365 The IDEs seem to have excellent support for the \ExtractMethod refactoring, so 
366 at least they have all passed the first refactoring 
367 rubicon\citing{fowlerRubicon2001,secondRubicon2012}.
368
369 Regarding the \MoveMethod refactoring, the \emph{Eclipse} and \emph{IntelliJ} 
370 IDEs do the job in very similar manners. In most situations they both do a 
371 satisfying job by producing the expected outcome. But they do nothing to check 
372 that the result does not break the semantics of the program. \See{correctness} 
373 The \emph{NetBeans} IDE implements this refactoring in a somewhat clumsy way.  
374 For starters, its default destination for the move is itself, although it 
375 refuses to perform the refactoring if chosen. But the worst part is, that if 
376 moving the method \method{f} of the below code to \type{X}, it will break the 
377 code. Given
378
379 \begin{minted}[samepage]{java}
380 public class C {
381     private X x;
382     ...
383     public void f() {
384         x.m();
385         x.n();
386     }
387 }
388 \end{minted}
389
390 \noindent the move refactoring will produce the following in class \type{X}:
391
392 \begin{minted}[samepage]{java}
393 public class X {
394     ...
395     public void f(C c) {
396         c.x.m();
397         c.x.n();
398     }
399 }
400 \end{minted}
401
402 NetBeans will try to make code that call the methods \method{m} and \method{n} 
403 of \type{X} by accessing them through \var{c.x}, where \var{c} is a parameter of 
404 type \type{C} that is added the method \method{f} when it is moved.  If 
405 \var{c.x} for some reason is inaccessible to \type{X}, as in this case, the 
406 refactoring breaks the code, and it will not compile. It has a preview of the 
407 refactoring outcome, but that does not catch that it is about to do something 
408 stupid. Ironically, this ``feature'' of NetBeans keeps it from breaking the code 
409 in the example from section \ref{correctness}.
410
411 The IDEs under investigation seems to have fairly good support for primitive 
412 refactorings, but what about more complex ones, such as the \refactoring{Extract 
413 Class}\citing{refactoring}? The \refactoring{Extract Class} refactoring works by 
414 creating a class, for then to move members to that class and access them from 
415 the old class via a reference to the new class. \emph{IntelliJ} seems to handle 
416 this in a fairly good manner, although, in the case of private methods, it 
417 leaves unused methods behind. These are methods that delegate to a field of the 
418 new class, but are not used anywhere. \emph{Eclipse} has added (or withdrawn) 
419 its own fun twist to the refactoring, and only allows for \emph{fields} to be 
420 moved to a new class. This makes it effectively only extracting a data 
421 structure, and calling it \refactoring{Extract Class} is a little misleading.  
422 One would often be better off with textual extract and paste than using the 
423 Extract Class refactoring in Eclipse. When it comes to \emph{NetBeans}, it does 
424 not even seem to have made an attempt on providing this refactoring. (Well, 
425 probably has, but it does not show in the IDE.) 
426
427 \todoin{Visual Studio (C++/C\#), Smalltalk refactoring browser?,
428 second refactoring rubicon?}
429
430 \section{The relation to design patterns}\label{relationToDesignPatterns}
431
432 \emph{Refactoring} and \emph{design patterns} have at least one thing in common, 
433 they are both promoted by advocates of \emph{clean code}\citing{cleanCode} as 
434 fundamental tools on the road to more maintanable and extendable source code.
435
436 \begin{quote}
437   Design patterns help you determine how to reorganize a design, and they can 
438   reduce the amount of refactoring you need to do 
439   later.~\cite[p.~353]{designPatterns}
440 \end{quote}
441
442 Although frequently associated with over-engineering, design patterns are in 
443 general assumed to be good for maintainability of source code. That may be 
444 because many of them are designed to support the \emph{open/closed principle} of 
445 object-oriented programming. The principle was first formulated by Bertrand 
446 Meyer, the creator of the Eiffel programming language, like this: ``Modules 
447 should be both open and closed.''\citing{meyer1988} It has been popularized, 
448 with this as a common version: 
449
450 \begin{quote}
451   Software entities (classes, modules, functions, etc.) should be open for 
452   extension, but closed for modification.\footnote{See 
453     \url{http://c2.com/cgi/wiki?OpenClosedPrinciple} or  
454     \url{https://en.wikipedia.org/wiki/Open/closed_principle}}
455 \end{quote} 
456
457 Maintainability is often thought of as the ability to be able to introduce new 
458 functionality without having to change to much of the old code. When 
459 refactoring, the motivation is often to facilitate adding new functionality. It 
460 is about factoring the old code in a way that makes the new functionality being 
461 able to benefit from the functionality already residing in a software system, 
462 without having to copy old code into new. Then, next time someone shall add new 
463 functionality, it is less likely that the old code have to change. Assuming that 
464 a design pattern is the best way to get rid of some case of duplication and 
465 assist in implementing new functionality, it is reasonable to conclude that a 
466 design pattern often is the target of a series of refactorings. Having a 
467 repertoire of design patterns can also help in knowing when and how to refactor 
468 a program to make it reflect certain desired characteristics.
469
470 \begin{quote}
471   There is a natural relation between patterns ans refactorings. Patterns are 
472   where you want to be; refactorings are ways to get there from somewhere 
473   else.~\cite[p.~107]{refactoring}
474 \end{quote}
475
476 This quote is wise in many contexts, but it is not always appropriate to say 
477 ``Patterns are where you want to be\ldots''. \emph{Sometimes}, patterns is where 
478 you want to be, but only because it will benefit your design. It is not true 
479 that one should always try to incorporate as many design patterns as possible 
480 into a program. It is not like they have intrinsic value. They only add value to 
481 a system when they support its design. Otherwise, the use of design patterns may 
482 only lead to a program that is more complex than necessary.
483
484 \begin{quote}
485   The overuse of patterns tends to result from being patterns happy. We are 
486   \emph{patterns happy} when we become so enamored of patterns that we simply 
487   must use them in our code.~\cite[p.~24]{kerievsky2005}
488 \end{quote}
489
490 This can easily happen when relying largely on up-front design. Then it is 
491 natural, in the very beginning, to try to build in all the flexibility that one 
492 believes will be necessary throughout the lifetime of a software system.  
493 According to Joshua Kerievsky ``That sounds reasonable --- if you happen to be 
494 psychic.''~\cite[p.~1]{kerievsky2005} He is advocating what he believes is a 
495 better approach: To let software continually evolve. To start with a simple 
496 design that meets today's needs, and tackle future needs by refactoring to 
497 satisfy them. He believes that this is a more economic approach than investing 
498 time and money into a design that inevitably is going to change. By relying on 
499 continuously refactoring a system, its design can be made simpler without 
500 sacrificing flexibility. To be able to fully rely on this approach, it is of 
501 utter importance to have a reliable suit of tests to lean on. \See{testing} This 
502 makes the design process more natural and less characterized by difficult 
503 decisions that has to be made before proceeding in the process, and that is 
504 going to define a project for all of its unforeseeable future.
505
506 \begin{comment}
507
508 \section{Classification of refactorings} 
509 % only interesting refactorings
510 % with 2 detailed examples? One for structured and one for intra-method?
511 % Is replacing Bubblesort with Quick Sort considered a refactoring?
512
513 \subsection{Structural refactorings}
514
515 \subsubsection{Primitive refactorings}
516
517 % Composing Methods
518 \explanation{Extract Method}{You have a code fragment that can be grouped 
519 together.}{Turn the fragment into a method whose name explains the purpose of 
520 the method.}
521
522 \explanation{Inline Method}{A method's body is just as clear as its name.}{Put 
523 the method's body into the body of its callers and remove the method.}
524
525 \explanation{Inline Temp}{You have a temp that is assigned to once with a simple 
526 expression, and the temp is getting in the way of other refactorings.}{Replace 
527 all references to that temp with the expression}
528
529 % Moving Features Between Objects
530 \explanation{Move Method}{A method is, or will be, using or used by more 
531 features of another class than the class on which it is defined.}{Create a new 
532 method with a similar body in the class it uses most. Either turn the old method 
533 into a simple delegation, or remove it altogether.}
534
535 \explanation{Move Field}{A field is, or will be, used by another class more than 
536 the class on which it is defined}{Create a new field in the target class, and 
537 change all its users.}
538
539 % Organizing Data
540 \explanation{Replace Magic Number with Symbolic Constant}{You have a literal 
541 number with a particular meaning.}{Create a constant, name it after the meaning, 
542 and replace the number with it.}
543
544 \explanation{Encapsulate Field}{There is a public field.}{Make it private and 
545 provide accessors.}
546
547 \explanation{Replace Type Code with Class}{A class has a numeric type code that 
548 does not affect its behavior.}{Replace the number with a new class.}
549
550 \explanation{Replace Type Code with Subclasses}{You have an immutable type code 
551 that affects the behavior of a class.}{Replace the type code with subclasses.}
552
553 \explanation{Replace Type Code with State/Strategy}{You have a type code that 
554 affects the behavior of a class, but you cannot use subclassing.}{Replace the 
555 type code with a state object.}
556
557 % Simplifying Conditional Expressions
558 \explanation{Consolidate Duplicate Conditional Fragments}{The same fragment of 
559 code is in all branches of a conditional expression.}{Move it outside of the 
560 expression.}
561
562 \explanation{Remove Control Flag}{You have a variable that is acting as a 
563 control flag fro a series of boolean expressions.}{Use a break or return 
564 instead.}
565
566 \explanation{Replace Nested Conditional with Guard Clauses}{A method has 
567 conditional behavior that does not make clear the normal path of 
568 execution.}{Use guard clauses for all special cases.}
569
570 \explanation{Introduce Null Object}{You have repeated checks for a null 
571 value.}{Replace the null value with a null object.}
572
573 \explanation{Introduce Assertion}{A section of code assumes something about the 
574 state of the program.}{Make the assumption explicit with an assertion.}
575
576 % Making Method Calls Simpler
577 \explanation{Rename Method}{The name of a method does not reveal its 
578 purpose.}{Change the name of the method}
579
580 \explanation{Add Parameter}{A method needs more information from its 
581 caller.}{Add a parameter for an object that can pass on this information.}
582
583 \explanation{Remove Parameter}{A parameter is no longer used by the method 
584 body.}{Remove it.}
585
586 %\explanation{Parameterize Method}{Several methods do similar things but with 
587 %different values contained in the method.}{Create one method that uses a 
588 %parameter for the different values.}
589
590 \explanation{Preserve Whole Object}{You are getting several values from an 
591 object and passing these values as parameters in a method call.}{Send the whole 
592 object instead.}
593
594 \explanation{Remove Setting Method}{A field should be set at creation time and 
595 never altered.}{Remove any setting method for that field.}
596
597 \explanation{Hide Method}{A method is not used by any other class.}{Make the 
598 method private.}
599
600 \explanation{Replace Constructor with Factory Method}{You want to do more than 
601 simple construction when you create an object}{Replace the constructor with a 
602 factory method.}
603
604 % Dealing with Generalization
605 \explanation{Pull Up Field}{Two subclasses have the same field.}{Move the field 
606 to the superclass.}
607
608 \explanation{Pull Up Method}{You have methods with identical results on 
609 subclasses.}{Move them to the superclass.}
610
611 \explanation{Push Down Method}{Behavior on a superclass is relevant only for 
612 some of its subclasses.}{Move it to those subclasses.}
613
614 \explanation{Push Down Field}{A field is used only by some subclasses.}{Move the 
615 field to those subclasses}
616
617 \explanation{Extract Interface}{Several clients use the same subset of a class's 
618 interface, or two classes have part of their interfaces in common.}{Extract the 
619 subset into an interface.}
620
621 \explanation{Replace Inheritance with Delegation}{A subclass uses only part of a 
622 superclasses interface or does not want to inherit data.}{Create a field for the 
623 superclass, adjust methods to delegate to the superclass, and remove the 
624 subclassing.}
625
626 \explanation{Replace Delegation with Inheritance}{You're using delegation and 
627 are often writing many simple delegations for the entire interface}{Make the 
628 delegating class a subclass of the delegate.}
629
630 \subsubsection{Composite refactorings}
631
632 % Composing Methods
633 % \explanation{Replace Method with Method Object}{}{}
634
635 % Moving Features Between Objects
636 \explanation{Extract Class}{You have one class doing work that should be done by 
637 two}{Create a new class and move the relevant fields and methods from the old 
638 class into the new class.}
639
640 \explanation{Inline Class}{A class isn't doing very much.}{Move all its features 
641 into another class and delete it.}
642
643 \explanation{Hide Delegate}{A client is calling a delegate class of an 
644 object.}{Create Methods on the server to hide the delegate.}
645
646 \explanation{Remove Middle Man}{A class is doing to much simple delegation.}{Get 
647 the client to call the delegate directly.}
648
649 % Organizing Data
650 \explanation{Replace Data Value with Object}{You have a data item that needs 
651 additional data or behavior.}{Turn the data item into an object.}
652
653 \explanation{Change Value to Reference}{You have a class with many equal 
654 instances that you want to replace with a single object.}{Turn the object into a 
655 reference object.}
656
657 \explanation{Encapsulate Collection}{A method returns a collection}{Make it 
658 return a read-only view and provide add/remove methods.}
659
660 % \explanation{Replace Array with Object}{}{}
661
662 \explanation{Replace Subclass with Fields}{You have subclasses that vary only in 
663 methods that return constant data.}{Change the methods to superclass fields and 
664 eliminate the subclasses.}
665
666 % Simplifying Conditional Expressions
667 \explanation{Decompose Conditional}{You have a complicated conditional 
668 (if-then-else) statement.}{Extract methods from the condition, then part, an 
669 else part.}
670
671 \explanation{Consolidate Conditional Expression}{You have a sequence of 
672 conditional tests with the same result.}{Combine them into a single conditional 
673 expression and extract it.}
674
675 \explanation{Replace Conditional with Polymorphism}{You have a conditional that 
676 chooses different behavior depending on the type of an object.}{Move each leg 
677 of the conditional to an overriding method in a subclass. Make the original 
678 method abstract.}
679
680 % Making Method Calls Simpler
681 \explanation{Replace Parameter with Method}{An object invokes a method, then 
682 passes the result as a parameter for a method. The receiver can also invoke this 
683 method.}{Remove the parameter and let the receiver invoke the method.}
684
685 \explanation{Introduce Parameter Object}{You have a group of parameters that 
686 naturally go together.}{Replace them with an object.}
687
688 % Dealing with Generalization
689 \explanation{Extract Subclass}{A class has features that are used only in some 
690 instances.}{Create a subclass for that subset of features.}
691
692 \explanation{Extract Superclass}{You have two classes with similar 
693 features.}{Create a superclass and move the common features to the 
694 superclass.}
695
696 \explanation{Collapse Hierarchy}{A superclass and subclass are not very 
697 different.}{Merge them together.}
698
699 \explanation{Form Template Method}{You have two methods in subclasses that 
700 perform similar steps in the same order, yet the steps are different.}{Get the 
701 steps into methods with the same signature, so that the original methods become 
702 the same. Then you can pull them up.}
703
704
705 \subsection{Functional refactorings}
706
707 \explanation{Substitute Algorithm}{You want to replace an algorithm with one 
708 that is clearer.}{Replace the body of the method with the new algorithm.}
709
710 \end{comment}
711
712 \section{The impact on software quality}
713
714 \subsection{What is meant by quality?}
715 The term \emph{software quality} has many meanings. It all depends on the 
716 context we put it in. If we look at it with the eyes of a software developer, it 
717 usually mean that the software is easily maintainable and testable, or in other 
718 words, that it is \emph{well designed}. This often correlates with the 
719 management scale, where \emph{keeping the schedule} and \emph{customer 
720 satisfaction} is at the center. From the customers point of view, in addition to 
721 good usability, \emph{performance} and \emph{lack of bugs} is always 
722 appreciated, measurements that are also shared by the software developer. (In 
723 addition, such things as good documentation could be measured, but this is out 
724 of the scope of this document.)
725
726 \subsection{The impact on performance}
727 \begin{quote}
728   Refactoring certainly will make software go more slowly, but it also makes the 
729   software more amenable to performance tuning.~\cite[p.~69]{refactoring}
730 \end{quote}
731
732 \noindent There is a common belief that refactoring compromises performance, due 
733 to increased degree of indirection and that polymorphism is slower than 
734 conditionals.
735
736 In a survey, Demeyer\citing{demeyer2002} disproves this view in the case of 
737 polymorphism. He is doing an experiment on, what he calls, ``Transform Self Type 
738 Checks'' where you introduce a new polymorphic method and a new class hierarchy 
739 to get rid of a class' type checking of a ``type attribute``. He uses this kind 
740 of transformation to represent other ways of replacing conditionals with 
741 polymorphism as well. The experiment is performed on the C++ programming 
742 language and with three different compilers and platforms. \todo{But is the 
743 result better?} Demeyer concludes that, with compiler optimization turned on, 
744 polymorphism beats middle to large sized if-statements and does as well as 
745 case-statements.  (In accordance with his hypothesis, due to similarities 
746 between the way C++ handles polymorphism and case-statements.)
747
748 \begin{quote}
749   The interesting thing about performance is that if you analyze most programs, 
750   you find that they waste most of their time in a small fraction of the 
751   code.~\cite[p.~70]{refactoring}
752 \end{quote}
753
754 \noindent So, although an increased amount of method calls could potentially 
755 slow down programs, one should avoid premature optimization and sacrificing good 
756 design, leaving the performance tuning until after profiling\footnote{For and 
757   example of a Java profiler, check out VisualVM: 
758   \url{http://visualvm.java.net/}} the software and having isolated the actual 
759   problem areas.
760
761 \section{Composite refactorings}\label{compositeRefactorings}
762 \todo{motivation, examples, manual vs automated?, what about refactoring in a 
763 very large code base?}
764 Generally, when thinking about refactoring, at the mechanical level, there are 
765 essentially two kinds of refactorings. There are the \emph{primitive} 
766 refactorings, and the \emph{composite} refactorings. A primitive refactoring can 
767 be defined like this:
768
769 \definition{A \emph{primitive refactoring} is a refactoring that cannot be 
770 expressed in terms of other refactorings.}
771
772 \noindent Examples are the \refactoring{Pull Up Field} and \refactoring{Pull Up 
773 Method} refactorings\citing{refactoring}, that moves members up in their class 
774 hierarchies.
775
776 A composite refactoring is more complex, and can be defined like this:
777
778 \definition{A \emph{composite refactoring} is a refactoring that can be 
779 expressed in terms of two or more other refactorings.}
780
781 \noindent An example of a composite refactoring is the \refactoring{Extract 
782 Superclass} refactoring\citing{refactoring}. In its simplest form, it is composed 
783 of the previously described primitive refactorings, in addition to the 
784 \refactoring{Pull Up Constructor Body} refactoring\citing{refactoring}.  It works 
785 by creating an abstract superclass that the target class(es) inherits from, then 
786 by applying \refactoring{Pull Up Field}, \refactoring{Pull Up Method} and 
787 \refactoring{Pull Up Constructor Body} on the members that are to be members of 
788 the new superclass. For an overview of the \refactoring{Extract Superclass} 
789 refactoring, see figure \ref{fig:extractSuperclass}.
790
791 \begin{figure}[h]
792   \centering
793   \includegraphics[angle=270,width=\linewidth]{extractSuperclassItalic.pdf}
794   \caption{The Extract Superclass refactoring}
795   \label{fig:extractSuperclass}
796 \end{figure}
797
798 \section{Manual vs. automated refactorings}
799 Refactoring is something every programmer does, even if \heshe does not known 
800 the term \emph{refactoring}. Every refinement of source code that does not alter 
801 the program's behavior is a refactoring. For small refactorings, such as 
802 \ExtractMethod, executing it manually is a manageable task, but is still prone 
803 to errors. Getting it right the first time is not easy, considering the 
804 signature and all the other aspects of the refactoring that has to be in place.  
805
806 Take for instance the renaming of classes, methods and fields. For complex 
807 programs these refactorings are almost impossible to get right.  Attacking them 
808 with textual search and replace, or even regular expressions, will fall short on 
809 these tasks. Then it is crucial to have proper tool support that can perform 
810 them automatically. Tools that can parse source code and thus has semantic 
811 knowledge about which occurrences of which names that belongs to what construct 
812 in the program. For even trying to perform one of these complex task manually, 
813 one would have to be very confident on the existing test suite \see{testing}.
814
815 \section{Correctness of refactorings}\label{correctness}
816 For automated refactorings to be truly useful, they must show a high degree of 
817 behavior preservation. This last sentence might seem obvious, but there are 
818 examples of refactorings in existing tools that break programs. I will now 
819 present an example of an \ExtractMethod refactoring followed by a \MoveMethod 
820 refactoring that breaks a program in both the \emph{Eclipse} and \emph{IntelliJ} 
821 IDEs\footnote{The NetBeans IDE handles this particular situation, mainly because 
822   its Move Method refactoring implementation is crippled in other ways
823   \see{toolSupport}.}. The following piece of code shows the target for the 
824   composed refactoring:
825
826 \begin{minted}[linenos,samepage]{java}
827 public class C {
828     public X x = new X();
829
830     public void f() {
831         x.m(this);
832         x.n();
833     }
834 }
835 \end{minted}
836
837 \noindent The next piece of code shows the destination of the refactoring. Note 
838 that the method \method{m(C c)} of class \type{C} assigns to the field \var{x} 
839 of the argument \var{c} that has type \type{C}:
840
841 \begin{minted}[samepage]{java}
842 public class X {
843     public void m(C c) {
844         c.x = new X();
845     }
846     public void n() {}
847 }
848 \end{minted}
849
850 The refactoring sequence works by extracting line 5 and 6 from the original 
851 class \type{C} into a method \method{f} with the statements from those lines as 
852 its method body. The method is then moved to the class \type{X}. The result is 
853 shown in the following two pieces of code:
854
855 \begin{minted}[linenos,samepage]{java}
856 public class C {
857     public X x = new X();
858
859     public void f() {
860         x.f(this);
861     }
862 }
863 \end{minted}
864
865 \begin{minted}[linenos,samepage]{java}
866 public class X {
867     public void m(C c) {
868         c.x = new X();
869     }
870     public void n() {}
871     public void f(C c) {
872         m(c);
873         n();
874     }
875 }
876 \end{minted}
877
878 After the refactoring, the method \method{f} of class \type{C} calls the method 
879 \method{f} of class \type{X}, and the program breaks.  (See line 5 of the 
880 version of class \type{C} after the refactoring.) Before the refactoring, the 
881 methods \method{m} and \method{n} of class \type{X} are called on different 
882 object instances (see line 5 and 6 of the original class \type{C}). After, they 
883 are called on the same object, and the statement on line 3 of class \type{X} 
884 (the version after the refactoring) no longer have any effect in our example.
885
886 The bug introduced in the previous example is of such a nature that it is very 
887 difficult to spot if the refactored code is not covered by tests. It does not 
888 generate compilation errors, and will thus only result in a runtime error or 
889 corrupted data, which might be hard to detect.
890
891 \section{Refactoring and testing}\label{testing}
892 \begin{quote}
893   If you want to refactor, the essential precondition is having solid 
894   tests.\citing{refactoring}
895 \end{quote}
896
897 When refactoring, there are roughly two kinds of errors that can be made. There 
898 are errors that make the code unable to compile, and there are the silent 
899 errors, only popping up at runtime. Compile-time errors are the nice ones. They 
900 flash up at the moment they are made (at least when using an IDE), and are 
901 usually easy to fix. The other kind of error is the dangerous one. It is the 
902 kind of error introduced in the example of section \ref{correctness}. It is an 
903 error sneaking into your code without you noticing, maybe. For discovering those 
904 kind of errors when refactoring, it is essential to have good test coverage. It 
905 is not a way to \emph{prove} that the code is correct, but it is a way to make 
906 you confindent that it \emph{probably} works as desired. In the context of test 
907 driven development, the tests are even a way to define how the program is 
908 supposed to work. It is then, by definition, working if the tests are passing.  
909
910 If the test coverage for a code base is perfect, then it should, theoretically, 
911 be risk-free to perform refactorings on it. This is why tests and refactoring is 
912 such a great match.
913
914 \section{Software metrics}
915 \todoin{Is this the appropriate place to have this section?}
916
917 %\part{The project}
918 %\chapter{Planning the project}
919 %\part{Conclusion}
920 %\chapter{Results}                   
921
922
923
924 \chapter{\ldots}
925 \todoin{write}
926 \section{The problem statement}
927 \section{Choosing the target language}
928 Choosing which programming language to use as the target for manipulation is not 
929 a very difficult task. The language have to be an object-oriented programming 
930 language, and it must have existing tool support for refactoring. The 
931 \emph{Java} programming language\footnote{\url{https://www.java.com/}} is the 
932 dominating language when it comes to examples in the literature of refactoring, 
933 and is thus a natural choice. Java is perhaps, currently the most influential 
934 programming language in the world, with its \emph{Java Virtual Machine} that 
935 runs on all of the most popular architectures and also supports\footnote{They 
936 compile to java bytecode.} dozens of other programming languages, with 
937 \emph{Scala}, \emph{Clojure} and \emph{Groovy} as the most prominent ones. Java 
938 is currently the language that every other programming language is compared 
939 against. It is also the primary language of the author of this thesis.
940
941 \section{Choosing the tools}
942 When choosing a tool for manipulating Java, there are certain criterias that 
943 have to be met. First of all, the tool should have some existing refactoring 
944 support that this thesis can build upon. Secondly it should provide some kind of 
945 framework for parsing and analyzing Java source code. Third, it should itself be 
946 open source. This is both because of the need to be able to browse the code for 
947 the existing refactorings that is contained in the tool, and also because open 
948 source projects hold value in them selves. Another important aspect to consider 
949 is that open source projects of a certain size, usually has large communities of 
950 people connected to them, that are commited to answering questions regarding the 
951 use and misuse of the products, that to a large degree is made by the cummunity 
952 itself.
953
954 There is a certain class of tools that meet these criterias, namely the class of 
955 \emph{IDEs}\footnote{\emph{Integrated Development Environment}}. These are 
956 proagrams that is ment to support the whole production cycle of a cumputer 
957 program, and the most popular IDEs that support Java, generally have quite good 
958 refactoring support.
959
960 The main contenders for this thesis is the \emph{Eclipse IDE}, with the 
961 \emph{Java development tools} (JDT), the \emph{IntelliJ IDEA Community Edition} 
962 and the \emph{NetBeans IDE}. \See{toolSupport} Eclipse and NetBeans are both 
963 free, open source and community driven, while the IntelliJ IDEA has an open 
964 sourced community edition that is free of charge, but also offer an 
965 \emph{Ultimate Edition} with an extended set of features, at additional cost.  
966 All three IDEs supports adding plugins to extend their functionality and tools 
967 that can be used to parse and analyze Java source code. \todo{investigate if 
968 this is true} But one of the IDEs stand out as a favorite, and that is the 
969 \emph{Eclipse IDE}. This is the most popular\citing{javaReport2011} among them 
970 and seems to be de facto standard IDE for Java development regardless of 
971 platform.
972
973
974 \chapter{Refactorings in Eclipse JDT: Design, Shortcomings and Wishful 
975 Thinking}\label{ch:jdt_refactorings}
976
977 This chapter will deal with some of the design behind refactoring support in 
978 Eclipse, and the JDT in specific. After which it will follow a section about 
979 shortcomings of the refactoring API in terms of composition of refactorings. The 
980 chapter will be concluded with a section telling some of the ways the 
981 implementation of refactorings in the JDT could have worked to facilitate 
982 composition of refactorings.
983
984 \section{Design}
985 The refactoring world of Eclipse can in general be separated into two parts: The 
986 language independent part and the part written for a specific programming 
987 language -- the language that is the target of the supported refactorings.  
988 \todo{What about the language specific part?}
989
990 \subsection{The Language Toolkit}
991 The Language Toolkit, or LTK for short, is the framework that is used to 
992 implement refactorings in Eclipse. It is language independent and provides the 
993 abstractions of a refactoring and the change it generates, in the form of the 
994 classes \typewithref{org.eclipse.ltk.core.refactoring}{Refactoring} and 
995 \typewithref{org.eclipse.ltk.core.refactoring}{Change}. (There is also parts of 
996 the LTK that is concerned with user interaction, but they will not be discussed 
997 here, since they are of little value to us and our use of the framework.)
998
999 \subsubsection{The Refactoring Class}
1000 The abstract class \type{Refactoring} is the core of the LTK framework. Every 
1001 refactoring that is going to be supported by the LTK have to end up creating an 
1002 instance of one of its subclasses. The main responsibilities of subclasses of 
1003 \type{Refactoring} is to implement template methods for condition checking 
1004 (\methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{checkInitialConditions} 
1005 and 
1006 \methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{checkFinalConditions}), 
1007 in addition to the 
1008 \methodwithref{org.eclipse.ltk.core.refactoring.Refactoring}{createChange} 
1009 method that creates and returns an instance of the \type{Change} class.
1010
1011 If the refactoring shall support that others participate in it when it is 
1012 executed, the refactoring has to be a processor-based 
1013 refactoring\typeref{org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring}.  
1014 It then delegates to its given 
1015 \typewithref{org.eclipse.ltk.core.refactoring.participants}{RefactoringProcessor} 
1016 for condition checking and change creation.
1017
1018 \subsubsection{The Change Class}
1019 This class is the base class for objects that is responsible for performing the 
1020 actual workspace transformations in a refactoring. The main responsibilities for 
1021 its subclasses is to implement the 
1022 \methodwithref{org.eclipse.ltk.core.refactoring.Change}{perform} and 
1023 \methodwithref{org.eclipse.ltk.core.refactoring.Change}{isValid} methods. The 
1024 \method{isValid} method verifies that the change object is valid and thus can be 
1025 executed by calling its \method{perform} method. The \method{perform} method 
1026 performs the desired change and returns an undo change that can be executed to 
1027 reverse the effect of the transformation done by its originating change object. 
1028
1029 \subsubsection{Executing a Refactoring}\label{executing_refactoring}
1030 The life cycle of a refactoring generally follows two steps after creation: 
1031 condition checking and change creation. By letting the refactoring object be 
1032 handled by a 
1033 \typewithref{org.eclipse.ltk.core.refactoring}{CheckConditionsOperation} that
1034 in turn is handled by a 
1035 \typewithref{org.eclipse.ltk.core.refactoring}{CreateChangeOperation}, it is 
1036 assured that the change creation process is managed in a proper manner.
1037
1038 The actual execution of a change object has to follow a detailed life cycle.  
1039 This life cycle is honored if the \type{CreateChangeOperation} is handled by a 
1040 \typewithref{org.eclipse.ltk.core.refactoring}{PerformChangeOperation}. If also 
1041 an undo manager\typeref{org.eclipse.ltk.core.refactoring.IUndoManager} is set 
1042 for the \type{PerformChangeOperation}, the undo change is added into the undo 
1043 history.
1044
1045 \section{Shortcomings}
1046 This section is introduced naturally with a conclusion: The JDT refactoring 
1047 implementation does not facilitate composition of refactorings. 
1048 \todo{refine}This section will try to explain why, and also identify other 
1049 shortcomings of both the usability and the readability of the JDT refactoring 
1050 source code.
1051
1052 I will begin at the end and work my way toward the composition part of this 
1053 section.
1054
1055 \subsection{Absence of Generics in Eclipse Source Code}
1056 This section is not only concerning the JDT refactoring API, but also large 
1057 quantities of the Eclipse source code. The code shows a striking absence of the 
1058 Java language feature of generics. It is hard to read a class' interface when 
1059 methods return objects or takes parameters of raw types such as \type{List} or 
1060 \type{Map}. This sometimes results in having to read a lot of source code to 
1061 understand what is going on, instead of relying on the available interfaces. In 
1062 addition, it results in a lot of ugly code, making the use of typecasting more 
1063 of a rule than an exception.
1064
1065 \subsection{Composite Refactorings Will Not Appear as Atomic Actions}
1066
1067 \subsubsection{Missing Flexibility from JDT Refactorings}
1068 The JDT refactorings are not made with composition of refactorings in mind. When 
1069 a JDT refactoring is executed, it assumes that all conditions for it to be 
1070 applied successfully can be found by reading source files that has been 
1071 persisted to disk. They can only operate on the actual source material, and not 
1072 (in-memory) copies thereof. This constitutes a major disadvantage when trying to 
1073 compose refactorings, since if an exception occur in the middle of a sequence of 
1074 refactorings, it can leave the project in a state where the composite 
1075 refactoring was executed only partly. It makes it hard to discard the changes 
1076 done without monitoring and consulting the undo manager, an approach that is not 
1077 bullet proof.
1078
1079 \subsubsection{Broken Undo History}
1080 When designing a composed refactoring that is to be performed as a sequence of 
1081 refactorings, you would like it to appear as a single change to the workspace.  
1082 This implies that you would also like to be able to undo all the changes done by 
1083 the refactoring in a single step. This is not the way it appears when a sequence 
1084 of JDT refactorings is executed. It leaves the undo history filled up with 
1085 individual undo actions corresponding to every single JDT refactoring in the 
1086 sequence. This problem is not trivial to handle in Eclipse. (See section 
1087 \ref{hacking_undo_history}.)
1088
1089 \section{Wishful Thinking}
1090
1091
1092
1093 \chapter{Composite Refactorings in Eclipse}
1094
1095 \section{A Simple Ad Hoc Model}
1096 As pointed out in chapter \ref{ch:jdt_refactorings}, the Eclipse JDT refactoring 
1097 model is not very well suited for making composite refactorings. Therefore a 
1098 simple model using changer objects (of type \type{RefaktorChanger}) is used as 
1099 an abstraction layer on top of the existing Eclipse refactorings.
1100
1101 \section{The Extract and Move Method Refactoring}
1102 %The Extract and Move Method Refactoring is implemented mainly using these 
1103 %classes:
1104 %\begin{itemize}
1105 %  \item \type{ExtractAndMoveMethodChanger}
1106 %  \item \type{ExtractAndMoveMethodPrefixesExtractor}
1107 %  \item \type{Prefix}
1108 %  \item \type{PrefixSet}
1109 %\end{itemize}
1110
1111 \subsection{The Building Blocks}
1112 This is a composite refactoring, and hence is built up using several primitive 
1113 refactorings. These basic building blocks are, as its name implies, the 
1114 \ExtractMethod refactoring\citing{refactoring} and the \MoveMethod 
1115 refactoring\citing{refactoring}. In Eclipse, the implementations of these 
1116 refactorings are found in the classes 
1117 \typewithref{org.eclipse.jdt.internal.corext.refactoring.code}{ExtractMethodRefactoring} 
1118 and 
1119 \typewithref{org.eclipse.jdt.internal.corext.refactoring.structure}{MoveInstanceMethodProcessor}, 
1120 where the last class is designed to be used together with the processor-based 
1121 \typewithref{org.eclipse.ltk.core.refactoring.participants}{MoveRefactoring}.
1122
1123 \subsubsection{The ExtractMethodRefactoring Class}
1124 This class is quite simple in its use. The only parameters it requires for 
1125 construction is a compilation 
1126 unit\typeref{org.eclipse.jdt.core.ICompilationUnit}, the offset into the source 
1127 code where the extraction shall start, and the length of the source to be 
1128 extracted. Then you have to set the method name for the new method together with 
1129 which access modifier that shall be used and some not so interesting parameters.
1130
1131 \subsubsection{The MoveInstanceMethodProcessor Class}
1132 For the Move Method the processor requires a little more advanced input than  
1133 the class for the Extract Method. For construction it requires a method 
1134 handle\typeref{org.eclipse.jdt.core.IMethod} from the Java Model for the method 
1135 that is to be moved. Then the target for the move have to be supplied as the 
1136 variable binding from a chosen variable declaration. In addition to this, one 
1137 have to set some parameters regarding setters/getters and delegation.
1138
1139 To make a whole refactoring from the processor, one have to construct a 
1140 \type{MoveRefactoring} from it.
1141
1142 \subsection{The ExtractAndMoveMethodChanger Class}
1143 The \typewithref{no.uio.ifi.refaktor.changers}{ExtractAndMoveMethodChanger} 
1144 class, that is a subclass of the class 
1145 \typewithref{no.uio.ifi.refaktor.changers}{RefaktorChanger}, is the class 
1146 responsible for composing the \type{ExtractMethodRefactoring} and the 
1147 \type{MoveRefactoring}. Its constructor takes a project 
1148 handle\typeref{org.eclipse.core.resources.IProject}, the method name for the new 
1149 method and a \typewithref{no.uio.ifi.refaktor.utils}{SmartTextSelection}.
1150
1151 A \type{SmartTextSelection} is basically a text 
1152 selection\typeref{org.eclipse.jface.text.ITextSelection} object that enforces 
1153 the providing of the underlying document during creation. I.e. its 
1154 \methodwithref{no.uio.ifi.refaktor.utils.SmartTextSelection}{getDocument} method 
1155 will never return \type{null}.
1156
1157 Before extracting the new method, the possible targets for the move operation is 
1158 found with the help of an
1159 \typewithref{no.uio.ifi.refaktor.extractors}{ExtractAndMoveMethodPrefixesExtractor}.  
1160 The possible targets is computed from the prefixes that the extractor returns 
1161 from its
1162 \methodwithref{no.uio.ifi.refaktor.extractors.ExtractAndMoveMethodPrefixesExtractor}{getSafePrefixes} 
1163 method. The changer then choose the most suitable target by finding the most 
1164 frequent occurring prefix among the safe ones. The target is the type of the 
1165 first part of the prefix.
1166
1167 After finding a suitable target, the \type{ExtractAndMoveMethodChanger} first 
1168 creates an \type{ExtractMethodRefactoring} and performs it as explained in 
1169 section \ref{executing_refactoring} about the execution of refactorings. Then it 
1170 creates and performs the \type{MoveRefactoring} in the same way, based on the 
1171 changes done by the Extract Method refactoring.
1172
1173 \subsection{The ExtractAndMoveMethodPrefixesExtractor Class}
1174 This extractor extracts properties needed for building the Extract and Move 
1175 Method refactoring. It searches through the given selection to find safe 
1176 prefixes, and those prefixes form a base that can be used to compute possible 
1177 targets for the move part of the refactoring.  It finds both the candidates, in 
1178 the form of prefixes, and the non-candidates, called unfixes. All prefixes (and 
1179 unfixes) are represented by a 
1180 \typewithref{no.uio.ifi.refaktor.extractors}{Prefix}, and they are collected 
1181 into prefix sets.\typeref{no.uio.ifi.refaktor.extractors.PrefixSet}. 
1182
1183 The prefixes and unfixes are found by property 
1184 collectors\typeref{no.uio.ifi.refaktor.extractors.collectors.PropertyCollector}.  
1185 A property collector follows the visitor pattern\citing{designPatterns} and is 
1186 of the \typewithref{org.eclipse.jdt.core.dom}{ASTVisitor} type.  An 
1187 \type{ASTVisitor} visits nodes in an abstract syntax tree that forms the Java 
1188 document object model. The tree consists of nodes of type 
1189 \typewithref{org.eclipse.jdt.core.do}{ASTNode}.
1190
1191 \subsubsection{The PrefixesCollector}
1192 The \typewithref{no.uio.ifi.refaktor.extractors.collectors}{PrefixesCollector} 
1193 is of type \type{PropertyCollector}. It visits expression 
1194 statements\typeref{org.eclipse.jdt.core.dom.ExpressionStatement} and creates 
1195 prefixes from its expressions in the case of method invocations. The prefixes 
1196 found is registered with a prefix set, together with all its sub-prefixes.
1197 \todo{Rewrite in the case of changes to the way prefixes are found}
1198
1199 \subsubsection{The UnfixesCollector}
1200 The \typewithref{no.uio.ifi.refaktor.extractors.collectors}{UnfixesCollector} 
1201 finds unfixes within the selection. An unfix is a name that is assigned to 
1202 within the selection. The reason that this cannot be allowed, is that the result 
1203 would be an assignment to the \type{this} keyword, which is not valid in Java.
1204
1205 \subsubsection{Computing Safe Prefixes}
1206 A safe prefix is a prefix that does not enclose an unfix. A prefix is enclosing 
1207 an unfix if the unfix is in the set of its sub-prefixes. As an example, 
1208 \texttt{``a.b''} is enclosing \texttt{``a''}, as is \texttt{``a''}. The safe 
1209 prefixes is unified in a \type{PrefixSet} and can be fetched calling the 
1210 \method{getSafePrefixes} method of the 
1211 \type{ExtractAndMoveMethodPrefixesExtractor}.
1212
1213 \subsection{The Prefix Class}
1214 \todo{?}
1215 \subsection{The PrefixSet Class}
1216
1217 \subsection{Hacking the Refactoring Undo 
1218 History}\label{hacking_undo_history}
1219 \todo{Where to put this section?}
1220
1221 As an attempt to make multiple subsequent changes to the workspace appear as a 
1222 single action (i.e. make the undo changes appear as such), I tried to alter 
1223 the undo changes\typeref{org.eclipse.ltk.core.refactoring.Change} in the history 
1224 of the refactorings.  
1225
1226 My first impulse was to remove the, in this case, last two undo changes from the 
1227 undo manager\typeref{org.eclipse.ltk.core.refactoring.IUndoManager} for the 
1228 Eclipse refactorings, and then add them to a composite 
1229 change\typeref{org.eclipse.ltk.core.refactoring.CompositeChange} that could be 
1230 added back to the manager. The interface of the undo manager does not offer a 
1231 way to remove/pop the last added undo change, so a possible solution could be to 
1232 decorate\citing{designPatterns} the undo manager, to intercept and collect the 
1233 undo changes before delegating to the \method{addUndo} 
1234 method\methodref{org.eclipse.ltk.core.refactoring.IUndoManager}{addUndo} of the 
1235 manager. Instead of giving it the intended undo change, a null change could be 
1236 given to prevent it from making any changes if run. Then one could let the 
1237 collected undo changes form a composite change to be added to the manager.
1238
1239 There is a technical challenge with this approach, and it relates to the undo 
1240 manager, and the concrete implementation 
1241 UndoManager2\typeref{org.eclipse.ltk.internal.core.refactoring.UndoManager2}.  
1242 This implementation is designed in a way that it is not possible to just add an 
1243 undo change, you have to do it in the context of an active 
1244 operation\typeref{org.eclipse.core.commands.operations.TriggeredOperations}.  
1245 One could imagine that it might be possible to trick the undo manager into 
1246 believing that you are doing a real change, by executing a refactoring that is 
1247 returning a kind of null change that is returning our composite change of undo 
1248 refactorings when it is performed.
1249
1250 Apart from the technical problems with this solution, there is a functional 
1251 problem: If it all had worked out as planned, this would leave the undo history 
1252 in a dirty state, with multiple empty undo operations corresponding to each of 
1253 the sequentially executed refactoring operations, followed by a composite undo 
1254 change corresponding to an empty change of the workspace for rounding of our 
1255 composite refactoring. The solution to this particular problem could be to 
1256 intercept the registration of the intermediate changes in the undo manager, and 
1257 only register the last empty change.
1258
1259 Unfortunately, not everything works as desired with this solution. The grouping 
1260 of the undo changes into the composite change does not make the undo operation 
1261 appear as an atomic operation. The undo operation is still split up into 
1262 separate undo actions, corresponding to the change done by its originating
1263 refactoring. And in addition, the undo actions has to be performed separate in 
1264 all the editors involved. This makes it no solution at all, but a step toward 
1265 something worse.
1266
1267 There might be a solution to this problem, but it remains to be found. The 
1268 design of the refactoring undo management is partly to be blamed for this, as it 
1269 it is to complex to be easily manipulated.
1270
1271
1272
1273 \chapter{Related Work}
1274
1275 \section{The compositional paradigm of refactoring}
1276 This paradigm builds upon the observation of Vakilian et 
1277 al.\citing{vakilian2012}, that of the many automated refactorings existing in 
1278 modern IDEs, the simplest ones are dominating the usage statistics. The report 
1279 mainly focuses on \emph{Eclipse} as the tool under investigation.
1280
1281 The paradigm is described almost as the opposite of automated composition of 
1282 refactorings \see{compositeRefactorings}. It works by providing the programmer 
1283 with easily accessible primitive refactorings. These refactorings shall be 
1284 accessed via keyboard shortcuts or quick-assist menus\footnote{Think 
1285 quick-assist with Ctrl+1 in Eclipse} and be promptly executed, opposed to in the 
1286 currently dominating wizard-based refactoring paradigm. They are ment to 
1287 stimulate composing smaller refactorings into more complex changes, rather than 
1288 doing a large upfront configuration of a wizard-based refactoring, before 
1289 previewing and executing it. The compositional paradigm of refactoring is 
1290 supposed to give control back to the programmer, by supporting \himher with an 
1291 option of performing small rapid changes instead of large changes with a lesser 
1292 degree of control. The report authors hope this will lead to fewer unsuccessful 
1293 refactorings. It also could lower the bar for understanding the steps of a 
1294 larger composite refactoring and thus also help in figuring out what goes wrong 
1295 if one should choose to op in on a wizard-based refactoring.
1296
1297 Vakilian and his associates have performed a survey of the effectiveness of the 
1298 compositional paradigm versus the wizard-based one. They claim to have found 
1299 evidence of that the \emph{compositional paradigm} outperforms the 
1300 \emph{wizard-based}. It does so by reducing automation, which seem 
1301 counterintuitive. Therefore they ask the question ``What is an appropriate level 
1302 of automation?'', and thus questions what they feel is a rush toward more 
1303 automation in the software engineering community.
1304
1305
1306 \backmatter{}
1307 \printbibliography
1308 \listoftodos
1309 \end{document}