What is refactoring? In simple words, it is just renaming of identifiers [1]. It is about changing the source code such that that there is no functional change in program’s behaviour. More can be read at http://en.wikipedia.org/wiki/Code_refactoring
The most basic application of refactoring is to rename a C/C++ identifier
[1]. This renaming is context sensitive. Eclipse knows whether
you are renaming something globally or locally. Just select the identifier
and press Ctrl + Shift + R
. The advantage over renaming? See an
example. The file example.c
has c_stream
in almost every function.
If we refactor c_stream
to cmprStream
in test_deflate
, the rename
would happen only in test_deflate
. c_stream
would remain as it is in
other function.
Here is refactoring/renaming in action. Select c_stream
and press
Ctrl + Shift + R
(Or ). A
dialog would pop up. Enter
the new name and press . Eclipse would show
Diff of the proposed changes. Here is a preview of
c_stream replaced with cmprStream
(The best use of refactoring this way is to rename local variables foo
,
bar
and the omnipresent int i=0
in loops)
Complex operations are difficult to read. If they are reduced with intermediate local variables, code becomes more readable. Eclipse can help to do that.
Select the expression
Press Ctrl + Shift + L
(Or ). Key in the local variable name (in this case
i_plus_j
)
Eclipse would replace the variable name.
Magic numbers are easy to write, and difficult to interpret later. Better replace with better meaning. Eclipse can help to do this, too.
Select the constant you want to replace. (In this case 10
)
Press Alt + C
(Or ).
Key in the new constant name (in this case TEN
)
Eclipse would replace all the 10
/ s with TEN
/ s
We can reduce a set of source lines to a meaningful function. It is not just copy/pasting code from one place to another. In some cases necessary local variables have to be passed in. Either by reference in CPP, or using pointers in C. Eclipse is intelligent enough to figure out the necessary local variables to be passed in. And also can figure out if they have to be passed using reference, pointers or just by value.
Select the source lines you want to extract as function.
Press Alt + Shift + M
(Or ). Key in the function name.
Eclipse would replace the source lines with a function call.
But, every selected source lines cannot be extracted to a function. We can
not extract lines with return
or break
.
[1] | (1, 2) Functions, variables, typedefs, enumerators, defines, etc. |