Refactoring – a new feature in the Visual C# 2.0 IDE
Extracting methods for repeated code
First let me show you some code, I'll then explain what it does and how I want to modify it, and how refactoring can help.
class TestClass
{
public void SendChatMessage(string message)
{
string filtered_message = message;
filtered_message = filtered_message.Trim();
filtered_message = filtered_message.ToUpper();
filtered_message = filtered_message.Replace("<some vulgar word>", string.Empty);
SendMessageOverNetwork(filtered_message);
}
public void SendMessageOverNetwork(string filtered_message)
{
//sends message over the network.
}
}
Ok, lets see what the code does.
There is a function called SendChatMessage, that takes a string. What this function is supposed to do is, take a string, which represents a message entered by a user in some chat application, and then calls a function SendMessageOcerNetwork to send it over the network. However, before it does that, it also "cleans" up the string a little bit, ie., it trims it, converts it to upper case (just for illustration purposes), and then removes occurrences of some words which are assumed to be too obscene to send to the other user.
Now, the code that performs the clean up above might also need to be used from other places within the application. Rather than duplicate this code everywhere, you decide to extract it to an auxiliary function, which you can then call from anywhere within your application. How can refactoring help you here? Easy. Just highlight the first 4 lines in the function above, choose "Refactor", and then "Extract method". Have a look at the images below and see how the code gets transformed.


