What is refactoring? In simple words, it is just renaming of identifiers . 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 . 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 Refactor ‣ Rename). 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)
188.8.131.52. Extract Local Variable¶
Complex operations are difficult to read. If they are reduced with intermediate local variables, code becomes more readable. Eclipse help to do that.
Select the expression
Press Ctrl + Shift + L (Or Refactor ‣ Extract Local Variable ). Key in the local variable name (in this case i_plus_j )
Eclipse would replace the variable name.
184.108.40.206. Extract Constants / Magic Numbers¶
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 Refactor ‣ Extract Constant). Key in the new constant name (in this case TEN)
Eclipse would replace all the 10/ s with TEN/ s
220.127.116.11. Extract Functions¶
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 Refactor ‣ Extract Function). 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, 2) Functions, variables, typedefs, enumerators, defines, etc.|