Blog

Filter posts by Category Or Tag of the Blog section!

Extract method refactoring in C#

Sunday, 29 September 2013

One of the best ways refactors a long method is to break it up into several methods. The extract method refactoring enables you to do this by selecting a block of code and select the Extract method and create a refactored extract method. Extract Method is just a refactoring operation that provides an easy way to create a new method from a code fragment in an existing member. You can create a new method by extracting a selection of the code from inside the code block of an existing member. Take a look at this example (don’t mention about the functionality of this method, I'm just going to refactor this method)

 

       public override string[] GetRolesForUser(string username)
        {
            using (var statosContext = new StatosContext())
            {
                var user = statosContext.Account.SingleOrDefault(u => u.UserName == username);
                if (user == null)
                    return new string[] { };
                return user.UserRoles == null ? new string[] { } :
                  user.UserRoles.Select(u => u.Role).Select(u => u.RoleName).ToArray();
            }
        }

 

If you are want to refactor the this, select the block of the code just like the picture

 

Refactoring

 

After selecting the Extract method, select a name for the extracted method (I selected RolesForUser)

 

     public override string[] GetRolesForUser(string username)
        {
            using (var statosContext = new StatosContext())
            {
                return RolesForUser(username, statosContext);
            }
        }

        private static string[] RolesForUser(string username, StatosContext statosContext)
        {
            var user = statosContext.Account.SingleOrDefault(u => u.UserName == username);
            if (user == null)
                return new string[] {};
            return user.UserRoles == null
                       ? new string[] {}
                       : user.UserRoles.Select(u => u.Role).Select(u => u.RoleName).ToArray();
        }

 

Now, this is a refactored code on extract method. I know there was no need in this method to refactor it, but in real-world programming, you definitely will have this kind of method which should be extracted to separated methods. 

Category: Software

Tags: C#

comments powered by Disqus