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