Refactoring


Many developers develop their applications first for functionality and then, once the functionality is in place, they re-work their applications to make them more manageable and more readable. This process is referred to as refactoring. Refactoring is the process of reworking code for readability, performance, providing type safety, and lining applications up to better adhere to standard OO (object-oriented) programming practices.

For this reason, the C# environment of Visual Studio 2005 now includes a set of refactoring tools. You can find these tools under the Refactoring option in the Visual Studio menu. To show this in action, create a new class called Car in Visual Studio:

 using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { public class Car { public string _color; public string _doors; public int Go() { int speedMph = 100; return speedMph; } } } 

Now from here, suppose that in the idea of refactoring, you want to change the code a bit so that the _color and the _door variables are encapsulated into public .NET properties. The refactoring capabilities of Visual Studio 2005 allow you to simply right-click either of these properties in the document window and select Refactor Encapsulate Field. This will pull up the Encapsulate Field dialog shown in Figure 14-28.

image from book
Figure 14-28

From this dialog, you can provide the name of the property and click the OK button. This will turn the selected public field into a private field while also encapsulating the field into a public .NET property. After clicking OK, the code will have been reworked to the following (after redoing both fields):

 using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { public class Car { private string _color; public string Color { get { return _color; } set { _color = value; } } private string _doors; public string Doors { get { return _doors; } set { _doors = value; } } public int Go() { int speedMph = 100; return speedMph; } } } 

As you can see, these wizards make it quite simple to refactor your code not just on one page but for an entire application. Also included are abilities to do the following:

  • Rename method names, local variables, fields, and more

  • Extract methods from a selection of code

  • Extract interfaces based upon a set of existing type members

  • Promote local variables to parameters

  • Rename or reorder parameters

You will find the new refactoring abilities provided by Visual Studio 2005 a great way to get you the cleaner, more readable, better structured code that you are looking for.




Professional C# 2005
Pro Visual C++ 2005 for C# Developers
ISBN: 1590596080
EAN: 2147483647
Year: 2005
Pages: 351
Authors: Dean C. Wills

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net