Lesson 2
Refactoring Long Methods with the Extract Method Technique in C#
Introduction & Context Setting

In our previous lesson, you learned how to eliminate duplicated code through method extraction and the refactoring of magic numbers. This lesson builds upon that foundation by applying it to another code smell. This technique is vital for transforming long, complex methods into smaller, more manageable ones, enhancing both readability and maintainability. As we delve into this lesson, remember that our goal is to follow the Test Driven Development (TDD) workflow: Red, Green, Refactor. This iterative cycle ensures that we can leverage our tests when refactoring to confirm that we have not changed anything about the behavior. If you change behavior, it is not a successful refactor.

Understanding the Problem with Long Methods

Long methods are a code smell that can be a hindrance to efficient development, as they often become difficult to understand, test, and maintain. A method might be considered long if it handles multiple responsibilities, making the code harder to track and debug. This complexity can impede our ability to effectively employ the TDD cycle, as isolated testing of functionalities becomes more challenging. Our task is to identify such cumbersome methods and employ the Extract Method technique to break them down into smaller, focused sub-methods, each with a single responsibility.

An Example of a Long Method

Take a look at the following method. Notice how it is not only long, but it is also responsible for doing a lot of things. Can you identify the different things this method is responsible for defining?

C#
1public class UserRegistrationService 2{ 3 private readonly IDataStore _dataStore; 4 5 public UserRegistrationService(IDataStore dataStore) 6 { 7 _dataStore = dataStore; 8 } 9 10 public RegistrationResponse ProcessUserRegistration(UserData userData) 11 { 12 try 13 { 14 // User validation 15 if (string.IsNullOrWhiteSpace(userData.Username) || userData.Username.Length < 3 || userData.Username.Length > 20) 16 { 17 return new RegistrationResponse(false, "Invalid username. Must be between 3 and 20 characters.", null); 18 } 19 20 if (string.IsNullOrWhiteSpace(userData.Email) || !userData.Email.Contains('@') || !userData.Email.Contains('.')) 21 { 22 return new RegistrationResponse(false, "Invalid email format.", null); 23 } 24 25 if (string.IsNullOrWhiteSpace(userData.Password) || userData.Password.Length < 8 || 26 !Regex.IsMatch(userData.Password, "[A-Z]") || 27 !Regex.IsMatch(userData.Password, "[0-9]") || 28 !Regex.IsMatch(userData.Password, "[!@#$%^&*]")) 29 { 30 return new RegistrationResponse(false, "Password must be at least 8 characters and contain uppercase, number, and special character.", null); 31 } 32 33 // Date validation 34 var birthDate = DateTime.Parse(userData.DateOfBirth); 35 var today = DateTime.Now; 36 var age = today.Year - birthDate.Year; 37 if (age < 18 || age > 120) 38 { 39 return new RegistrationResponse(false, "Invalid date of birth or user must be 18+", null); 40 } 41 42 // Address validation 43 if (string.IsNullOrWhiteSpace(userData.Address.Street) || userData.Address.Street.Length < 5) 44 { 45 return new RegistrationResponse(false, "Invalid street address", null); 46 } 47 if (string.IsNullOrWhiteSpace(userData.Address.City) || userData.Address.City.Length < 2) 48 { 49 return new RegistrationResponse(false, "Invalid city", null); 50 } 51 if (string.IsNullOrWhiteSpace(userData.Address.Country) || userData.Address.Country.Length < 2) 52 { 53 return new RegistrationResponse(false, "Invalid country", null); 54 } 55 if (string.IsNullOrWhiteSpace(userData.Address.PostalCode) || 56 !Regex.IsMatch(userData.Address.PostalCode, @"^[A-Z0-9]{3,10}$")) 57 { 58 return new RegistrationResponse(false, "Invalid postal code", null); 59 } 60 61 // Data transformation 62 var userId = $"USER_{Guid.NewGuid().ToString().Substring(0, 8)}"; 63 var normalizedData = new UserData 64 { 65 Username = userData.Username.ToLower(), 66 Email = userData.Email.ToLower(), 67 Password = userData.Password, 68 DateOfBirth = birthDate.ToString("yyyy-MM-dd"), 69 Address = new Address 70 { 71 Street = userData.Address.Street.Trim(), 72 City = userData.Address.City.Trim(), 73 Country = userData.Address.Country.ToUpper(), 74 PostalCode = userData.Address.PostalCode.ToUpper(), 75 } 76 }; 77 78 _dataStore.Store(normalizedData); 79 80 return new RegistrationResponse(true, "User registered successfully", userId); 81 } 82 catch (Exception e) 83 { 84 return new RegistrationResponse(false, $"Registration failed: {e.Message}", ""); 85 } 86 } 87}

The ProcessUserRegistration method performs multiple tasks:

  • User Validation: Checks that the username, email, and password meet specific criteria.
  • Date Validation: Verifies that the user’s date of birth is valid and within a specific age range.
  • Address Validation: Ensures that each part of the address (e.g., street, city, country, postal code) follows certain rules.
  • Data Transformation: Normalizes data (e.g., converting email and username to lowercase).
  • Data Storage: Saves the user data to the datastore.
  • Error Handling: Catches and returns any errors encountered.

By isolating each of these responsibilities into separate methods, we can improve readability and reusability, and make our code easier to maintain.

Refactor: Extract Method

We can extract the user validation functionality into its own method:

C#
1private RegistrationResponse ValidateUser(UserData userData) 2{ 3 if (string.IsNullOrWhiteSpace(userData.Username) || userData.Username.Length < 3 || userData.Username.Length > 20) 4 { 5 return new RegistrationResponse(false, "Invalid username. Must be between 3 and 20 characters.", null); 6 } 7 8 if (string.IsNullOrWhiteSpace(userData.Email) || !userData.Email.Contains('@') || !userData.Email.Contains('.')) 9 { 10 return new RegistrationResponse(false, "Invalid email format.", null); 11 } 12 13 if (string.IsNullOrWhiteSpace(userData.Password) || userData.Password.Length < 8 || 14 !Regex.IsMatch(userData.Password, "[A-Z]") || 15 !Regex.IsMatch(userData.Password, "[0-9]") || 16 !Regex.IsMatch(userData.Password, "[!@#$%^&*]")) 17 { 18 return new RegistrationResponse(false, "Password must be at least 8 characters and contain uppercase, number, and special character.", null); 19 } 20 21 return null; 22}
Benefits of the Extract Method

Applying the Extract Method makes our code more readable and allows for individual components to be reusable across our codebase. Testing specific functionalities separately enhances our debugging capabilities and reduces complexity. This approach aligns with the TDD principles of making small, incremental changes followed by comprehensive testing.

Review, Summary, and Next Steps

In this lesson, we have built on our refactoring skills by employing the Extract Method pattern to manage long methods within a class. Key takeaways include:

  • Identifying long methods and articulating their issues.
  • Reinforcing the benefits of maintainable and readable code through method extraction.

As you proceed, the upcoming practice exercises will give you hands-on experience in implementing these techniques. Continue applying TDD principles in your work for more efficient, robust, and scalable applications. Keep up the excellent work! You're well on your way to mastering clean and sustainable code practices.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.