Page 1 of 1

Refactoring Just how much time can you save?

#1 danny_kay1710  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 29
  • View blog
  • Posts: 359
  • Joined: 27-April 08

Posted 17 December 2008 - 05:16 PM

Refactoring in C#

Summary
• Rename
• Extract Method
• Encapsulate Field
• Extract Interface
• Promote Local Variable to Parameter
• Remove & Reorder Parameters

Rename
This is exactly what the title suggests. There is a feature in Visual Studio that will rename every instance of a given variable to a new name.
So let’s take a look at how to do it with an example of its uses.
Take the following code example:

Private void MyProc ()
{
	String myString = "Hello World";
	This.txtString.Text = myString;
}



Using the above code as an example, right click either instance of the variable myString and go to Refactor.. Rename.
A dialog box will popup asking you for a new name. If you leave the check box for “Preview reference changes” checked you will be shown a preview box of all the code that will be affected. You can also choose to replace instances of the variable name in comments and strings on this dialog box as well.
Type something different into the New name text box and click OK. Confirm the preview windows if prompted. The IDE will now have replaced all instances of that variable with the new name.

You may be thinking at this point why bother with it? In this case that is true but there are only two instances, in larger projects who knows how much time that could save you, especially when you don’t quite trust find and replace to only replace the instances of that variable and nothing else. Unlike Find & Replace you can be sure this only replaces what you want it to replace.

String myString;
Private void MyProc()
{
	String myString = “Hello World”;
	This.txtString.Text = myString;
}



Another point worth noting is that if you have the above code and you right clicked the global declaration (e.g. the declaration outside of the procedure) then it would not replace the variable names inside of the void MyProc. This is because it has been overridden by a local declaration of the same name. Similarly if you right click an instance of the variable within MyProc the IDE would not update the global declaration.

Extract Method

Again you may be able to guess what this does by its title. This takes a section of code and extracts it into its own method.
Now let’s take a look at what we need to do and how to do it.

private void Form1_Load(object sender, EventArgs e)
		{
			string strHelloWorld = "Hello World ";
			for (int i = 0; i <= 10; i++)
			{
				this.lstCount.Items.Add(strHelloWorld & Convert.ToString(i) & "!");
			}
	   }



OK, we want to move all the code into its own method. Now again before you say why bother just wait a minute.
Firstly lets select everything inside the curly braces of Form1_Load. Right Click your new selection and goto Refacter...Extract Method.
On the dialog box that will appear simply type the method name and click OK. The IDE then automatically creates the new method and calls it in the existing location. See Below

private void Form1_Load(object sender, EventArgs e)
{
		FillListBox();
}

private void FillListBox()
{
	   string strHelloWorld = "Hello World ";
	   for (int i = 0; i <= 10; i++)
	   {
			this.lstCount.Items.Add(strHelloWorld & Convert.ToString(i) & "!");
		}
}



So to add a little bit more appeal to just how powerful that is let’s try it again. This time just select the for loop (so don’t select the string declaration) and do the same thing. Notice how this time it creates a method with strHelloWorld as a parameter and automatically passes it. See Below:

private void Form1_Load(object sender, EventArgs e)
{
	string strHelloWorld = "Hello World ";
	FillListBox(strHelloWorld);
}

private void FillListBox(string strHelloWorld)
{
	for (int i = 0; i <= 10; i++)
	{
		this.lstCount.Items.Add(strHelloWorld & Convert.ToString(i) & "!");
	}
}



Encapsulate Field

This one may not be as obvious to some people as to exactly what it does, and along with Rename has to be one of my favourite Refactoring tools.
OK, so your creating a class which needs several variables with accessors. See code example below.

	class clsCar
	{
		private string strMake;
		private string strModel;
		private int intEngineSize;
		private bool boolCentralLocking;
		private bool boolElectricWindows;	 
	}
 


God only knows how many more you could probably come up with but that doesn’t matter at this point. But that’s the easy bit now you have to sit there and make a method with get and set properties so that it can be accessed publicly.

Well now there is a quicker way than typing them in yourselves. Place your cursor in or select one of your private variables. Again right click and goto Refactor...Encapsulate Field. Type in the name of the property into the dialog box and click OK. Click Apply on the second dialog and there you have it. Within seconds you can have would could easily have taken several minutes if not longer (depending on the amount of properties. See output below:

class clsCar
{
	private string strMake;

	public string StrMake
	{
		get { return strMake; }
		set { strMake = value; }
	}
	private string strModel;

	public string StrModel
	{
		get { return strModel; }
		set { strModel = value; }
	}
	private int intEngineSize;

	public int IntEngineSize
	{
		get { return intEngineSize; }
		set { intEngineSize = value; }
	}
	private bool boolCentralLocking;

	public bool BoolCentralLocking
	{
		get { return boolCentralLocking; }
		set { boolCentralLocking = value; }
	}
	private bool boolElectricWindows;

	public bool BoolElectricWindows
	{
		get { return boolElectricWindows; }
		set { boolElectricWindows = value; }
	}
}



Extract Interface

As you can probably tell by the title of the section. This extracts common elements of classes into an interface. (If you’re unsure about interfaces try this link http://msdn.microsof...5b(VS.80).aspx) This doesn’t care what you have selected as long as you have a public member. This can be anything from an accessor function to public functions or procedures.

Using the above output sample as a starting point simply right click (in the code window) goto Refactor...Extract Interface.

Select all of the public members to make an interface from and select the filename you want for the new interface. Then click OK.
You will now see that the IDE has made all the necessary changes in order to utilise an interface without you needing to go through the hassle of manually going through it all. See what it generates for you below if you select to create an interface for all members:

The class declaration changes to (where IclsCar is the name of the new file chosen on the dialog box):
class clsCar : WindowsFormsApplication1.IclsCar


The new interface file contains:

interface IclsCar
{
	bool BoolCentralLocking { get; set; }
	bool BoolElectricWindows { get; set; }
	int IntEngineSize { get; set; }
	string StrMake { get; set; }
	string StrModel { get; set; }
}




Promote Local Variable to parameter

This takes a locally declared variable and changes it to be a parameter as you probably already guessed

		private string GetValue()
		{
			int index = 0;
			return this.lstCount.Items[index].ToString();
		}



Take the above code. At the moment the function will always return the entry in the list box at position 0 which as functions go isn’t much use but a perfect example of where we could use Promote Local Variable to parameter.

Select the variable declaration for index. (NOTE: you must select the declaration not any instance of it.) and then Right click and goto Refactor.. Promote Local Variable to Parameter. If successful the changes should be seen immediately without any prompts or dialogs.

		private string GetValue(int index)
		{
			return this.lstCount.Items[index].ToString();
		}



Also note that declaration must initialise the variable as well or this will not work. Yet another reason why in your projects you should always initialise your variables.

Remove & Reorder Parameters

Yes, you guessed it this Refactoring method allows you to reorder & remove the parameters with a nice GUI dialog box instead of attempting to move text about the screen.
Unless there are a lot of parameters this may not save you time or be much easier but there may well come a time when it will help even if only slightly.
Right click and goto Refactor. Select whether you want to remove or reorder parameters from the menu. (Note that this will not work on lines where parameters are not present)
The Remove dialog box is simple enough with a list of all of your parameters and a remove button. Note that by clicking remove it doesn’t remove it from the list box, merely crosses it out in case you change your mind. By default as well it will let you see the new line before applying the final changes.
The Reorder dialog box again is relatively simple, with a list box and an up and down button. Again by default changes are not made when you click OK but after you click Apply on the second dialog box which shows you the new line.

Conclusion

I hope that this tutorial has helped someone to learn a bit more about the features available in the IDE when developing in C# and I hope that you have enjoyed reading this tutorial.
For jealous VB.NET programmers out there you do have a Rename function (on the right click menu in the code window) which is similar to the Rename refactoring option but unfortunately the rest of the options seem to be for C# only

Is This A Good Question/Topic? 2
  • +

Replies To: Refactoring

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1659
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Posted 18 December 2008 - 12:55 PM

Nice introduction to Refactoring and how it works Danny. Nice job :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1