Tutorial: Refactoring


Home » Support » Index of All Documentation » Introduction for New Users » Wing IDE Tutorial »

Refactoring is a general term for renaming or restructuring code in a way that does not alter its functionality. It is useful for cleaning up code or to prepare code for easier extension or reuse.

Wing implements a number of refactoring operations. Let's try some of these now in example1.py.

Rename Symbol

Right click on kCannedData in the import statement at the top of the file and select Rename Symbol from the Refactor sub-menu (or just click on kCannedData and select the operation from the Refactor menu).

Wing will bring the refactoring tool to the front and enumerates the points of use for the symbol you have selected:

/images/doc/en/intro/refactor-rename.png

Now enter kCannedTuna as the new name to use and press Enter or the Rename Checked button. Wing instantly renames all uses of the symbol.

Move Symbol

Now try moving PromptToContinue into subdir/path_example.py with the Move Symbol operation. In the refactoring tool, use Browse... to select subdir/path_example.py as the target location and leave Scope set to <module global scope>. Then press Move & Update Checked. Wing moves the point of definition into the target file and introduces the necessary import so it can still be used from example1.py.

Note that the whole module is imported and you would have to manually fix up the import if you wished to add the symbol to list in the from path_example import statement instead.

Extract Function/Method

Next select the first larger block in ReadPythonNews as follows:

/images/doc/en/intro/refactor-extract.png

Then select the Extract Function/Method refactoring operation and enter ReadNewsCache as the name for a new top-level function. Wing will create a new function and convert the point of use to a call to that function, as follows, inserting all the necesary arguments and return values:

txt = ReadNewsCache(force, newscache)

Click on ReadNewsCache and use F4 to visit its point of definition. Then use the history back arrow to get back to the point of use and press Revert in the Refactoring tool to undo this change.

Try it again now after selecting Nested Function instead to see how that operation differs. Then press Revert again.

Introduce Variable

Wing can also introduce new variables for an expression. For example, select time.time() - mtime in ReadPythonNews and use Introduce Variable to create a variable called duration. Wing inserts the variable and substitutes it into the original expression:

/images/doc/en/intro/refactor-introduce.png

If there had been multiple instances of time.time() - mtime in the scope, all of them would have been replaced.

« 1.10. Tutorial: Turbo Completion Mode (Experimental)Table of Contents1.12. Tutorial: Indentation Features »