Extract method refactoring in C#

One of the best ways refactor a long method is to break it up into several methods. The extract method refactoring enable 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 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)

  1.        public override string[] GetRolesForUser(string username)
  2.         {
  3.             using (var statosContext = new StatosContext())
  4.             {
  5.                 var user = statosContext.Account.SingleOrDefault(u => u.UserName == username);
  6.                 if (user == null)
  7.                     return new string[] { };
  8.                 return user.UserRoles == null ? new string[] { } :
  9.                   user.UserRoles.Select(u => u.Role).Select(u => u.RoleName).ToArray();
  10.             }
  11.         }

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)

  1.      public override string[] GetRolesForUser(string username)
  2.         {
  3.             using (var statosContext = new StatosContext())
  4.             {
  5.                 return RolesForUser(username, statosContext);
  6.             }
  7.         }
  8.  
  9.         private static string[] RolesForUser(string username, StatosContext statosContext)
  10.         {
  11.             var user = statosContext.Account.SingleOrDefault(u => u.UserName == username);
  12.             if (user == null)
  13.                 return new string[] {};
  14.             return user.UserRoles == null
  15.                        ? new string[] {}
  16.                        : user.UserRoles.Select(u => u.Role).Select(u => u.RoleName).ToArray();
  17.         }

 

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 kinds of method which should be extracted to separated methods. 


Tags: C#


comments powered by Disqus