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