Lesson 2
Long Method Refactoring: Extract Method Technique
Introduction & Context Setting

In our previous lesson, you learned how to eliminate duplicated code through function extraction and the refactoring of magic numbers. This lesson builds upon that foundation by introducing another crucial refactoring technique: the Extract Method. 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 to when refactoring to ensure 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 is 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 metnod is responsible for defining?

TypeScript
1processUserRegistration(userData: UserData): { success: boolean; message: string; userId?: string } { 2 try { 3 // Input validation 4 if (!userData.username || userData.username.length < 3 || userData.username.length > 20) { 5 return { success: false, message: "Invalid username. Must be between 3 and 20 characters." }; 6 } 7 8 if (!userData.email || !userData.email.includes('@') || !userData.email.includes('.')) { 9 return { success: false, message: "Invalid email format." }; 10 } 11 12 if (!userData.password || userData.password.length < 8 || 13 !/[A-Z]/.test(userData.password) || 14 !/[0-9]/.test(userData.password) || 15 !/[!@#$%^&*]/.test(userData.password)) { 16 return { 17 success: false, 18 message: "Password must be at least 8 characters and contain uppercase, number, and special character." 19 }; 20 } 21 22 // Date validation 23 const birthDate = new Date(userData.dateOfBirth); 24 const today = new Date(); 25 const age = today.getFullYear() - birthDate.getFullYear(); 26 if (isNaN(birthDate.getTime()) || age < 18 || age > 120) { 27 return { success: false, message: "Invalid date of birth or user must be 18+" }; 28 } 29 30 // Address validation 31 if (!userData.address.street || userData.address.street.length < 5) { 32 return { success: false, message: "Invalid street address" }; 33 } 34 if (!userData.address.city || userData.address.city.length < 2) { 35 return { success: false, message: "Invalid city" }; 36 } 37 if (!userData.address.country || userData.address.country.length < 2) { 38 return { success: false, message: "Invalid country" }; 39 } 40 if (!userData.address.postalCode || !/^[A-Z0-9]{3,10}$/.test(userData.address.postalCode)) { 41 return { success: false, message: "Invalid postal code" }; 42 } 43 44 // Data transformation 45 const userId = `USER_${Math.random().toString(36).substr(2, 9)}`; 46 const normalizedData = { 47 username: userData.username.toLowerCase(), 48 email: userData.email.toLowerCase(), 49 password: userData.password, 50 dateOfBirth: birthDate.toISOString(), 51 address: { 52 street: userData.address.street.trim(), 53 city: userData.address.city.trim(), 54 country: userData.address.country.toUpperCase(), 55 postalCode: userData.address.postalCode.toUpperCase(), 56 } 57 }; 58 59 this.dataStore.store(normalizedData); 60 61 return { 62 success: true, 63 message: "User registered successfully", 64 userId: userId 65 }; 66 } catch (error) { 67 return { 68 success: false, 69 message: `Registration failed: ${(error as Error).message}` 70 }; 71 } 72}

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:

TypeScript
1validateUser(userData: UserData) { 2 if (!userData.username || userData.username.length < 3 || userData.username.length > 20) { 3 return { success: false, message: "Invalid username. Must be between 3 and 20 characters." }; 4 } 5 6 if (!userData.email || !userData.email.includes('@') || !userData.email.includes('.')) { 7 return { success: false, message: "Invalid email format." }; 8 } 9 10 if (!userData.password || userData.password.length < 8 || 11 !/[A-Z]/.test(userData.password) || 12 !/[0-9]/.test(userData.password) || 13 !/[!@#$%^&*]/.test(userData.password)) { 14 return { 15 success: false, 16 message: "Password must be at least 8 characters and contain uppercase, number, and special character." 17 }; 18 } 19 20 return null; 21}
Benefits of the Extract Method

By applying the Extract Method, our code benefits by becoming more readable and allowing 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.