Refactoring: Rename method

One of the simplest refactoring methods is called Rename method. There are many reasons why one may want to change the name of some method. I think that main reason to rename a method is to give it a name that describes better what method is supposed to do.

Let’s see some code.

public class ProfileImporter
{
   
private List<Profile
> _profiles;

   
// More code here ...

   
public void
Import()
    {
       
foreach (var profile in
_profiles)
            ImportOne(profile);
    }

   
public void ImportOne(Profile
profile)
    {
       
// import profile data
    }
}

We can easily understand what this class does. It imports user profiles. Import method iterates through the list of previously loaded user profiles and imports them one by one. ImportOne method imports given profile and returns. Everything seems to be perfect but there is something annoying.

When we are looking at this class we may not notice that ImportOne is not informative name. But when we are using object based on that class then ImportOne doesn’t seem nice name. What it means “import one”? One what? How one is imported? It doesn’t make me feel comfortable when I have to call this method because I’m not sure what it exactly does.

Now I want to give better name to this method so I can be sure what it does and also other team members or customers can understand what this method exactly does. New name of the method will be ImportProfile. It is clear to everybody what this method does – it imports one profile. And as we can see from argument list we have to provide the profile we want to import.

Rename refactoringThis refactoring method is also supported by Visual Studio. Just move mouse pointer to method you want to rename, click right mouse button, select Refactor and then Rename. Also you can find that kind of functionality from famous coding tool Resharper.

It is good idea to use these tools when refactoring because renaming method calls manually may take much more time and also probability of making typos is high.

Automatic tools let you go through renaming process fast and there is less probability for errors. After renaming the method make sure you try to compile and test your code to make sure that refactoring didn’t introduced new errors.

Book recommendation! Those who want to find out more about refactoring and have a timeless hardcover handbook on the work desk should consider the book “Refactoring: Improving the Design of Existing Code” by Martin Fowler.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    Leave a Reply

    Your email address will not be published. Required fields are marked *