Refactoring – a new feature in the Visual C# 2.0 IDE
CoderSource.net
Refactoring – a new feature in the Visual C# 2.0 IDE - Article by muskad202
Level: BeginnerType: Article
Rating: Page: 4 of 4

Date: 4/23/2006 12:00:00 AM

Environment: Windows, Visual Studio .Net 2005

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.

 

1 2 3 4

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us