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 functions 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 hinder 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 function. Notice how it is not only long, but it is also responsible for doing a lot of things. Can you identify the different tasks this function is handling?

Swift
1func processUserRegistration(userData: [String: Any]) -> [String: Any] { 2 do { 3 guard let username = userData["username"] as? String, username.count >= 3, username.count <= 20 else { 4 return [ 5 "success": false, 6 "message": "Invalid username. Must be between 3 and 20 characters." 7 ] 8 } 9 10 guard let email = userData["email"] as? String, email.contains("@"), email.contains(".") else { 11 return ["success": false, "message": "Invalid email format."] 12 } 13 14 guard let password = userData["password"] as? String, password.count >= 8, 15 password.rangeOfCharacter(from: .uppercaseLetters) != nil, 16 password.rangeOfCharacter(from: .decimalDigits) != nil, 17 password.rangeOfCharacter(from: CharacterSet(charactersIn: "!@#$%^&*")) != nil else { 18 return [ 19 "success": false, 20 "message": "Password must be at least 8 characters and contain uppercase, number, and special character." 21 ] 22 } 23 24 guard let dateOfBirthString = userData["date_of_birth"] as? String, 25 let birthDate = ISO8601DateFormatter().date(from: dateOfBirthString) else { 26 return [ 27 "success": false, 28 "message": "Invalid date of birth format." 29 ] 30 } 31 32 let today = Date() 33 let ageComponents = Calendar.current.dateComponents([.year], from: birthDate, to: today) 34 guard let age = ageComponents.year, age >= 18, age <= 120 else { 35 return [ 36 "success": false, 37 "message": "Invalid date of birth or user must be 18+" 38 ] 39 } 40 41 guard let address = userData["address"] as? [String: String], 42 let street = address["street"], street.count >= 5, 43 let city = address["city"], city.count >= 2, 44 let country = address["country"], country.count >= 2, 45 let postalCode = address["postal_code"], postalCode.count >= 3, postalCode.rangeOfCharacter(from: .alphanumerics) != nil else { 46 return ["success": false, "message": "Invalid address details."] 47 } 48 49 let userId = "USER_" + (0..<9).map { _ in "abcdefghijklmnopqrstuvwxyz0123456789".randomElement()! }.joined() 50 51 let normalizedData: [String: Any] = [ 52 "username": username.lowercased(), 53 "email": email.lowercased(), 54 "password": password, 55 "date_of_birth": ISO8601DateFormatter().string(from: birthDate), 56 "address": [ 57 "street": street.trimmingCharacters(in: .whitespaces), 58 "city": city.trimmingCharacters(in: .whitespaces), 59 "country": country.uppercased(), 60 "postal_code": postalCode.uppercased() 61 ] 62 ] 63 64 // Assuming dataStore is a property of the class 65 try dataStore.store(normalizedData) 66 67 return [ 68 "success": true, 69 "message": "User registered successfully", 70 "user_id": userId 71 ] 72 } catch { 73 return [ 74 "success": false, 75 "message": "Registration failed: \(error.localizedDescription)" 76 ] 77 } 78}

The processUserRegistration function 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 function:

Swift
1func validateUser(userData: [String: Any]) -> [String: Any]? { 2 guard let username = userData["username"] as? String, username.count >= 3, username.count <= 20 else { 3 return [ 4 "success": false, 5 "message": "Invalid username. Must be between 3 and 20 characters." 6 ] 7 } 8 9 guard let email = userData["email"] as? String, email.contains("@"), email.contains(".") else { 10 return ["success": false, "message": "Invalid email format."] 11 } 12 13 guard let password = userData["password"] as? String, password.count >= 8, 14 password.rangeOfCharacter(from: .uppercaseLetters) != nil, 15 password.rangeOfCharacter(from: .decimalDigits) != nil, 16 password.rangeOfCharacter(from: CharacterSet(charactersIn: "!@#$%^&*")) != nil else { 17 return [ 18 "success": false, 19 "message": "Password must be at least 8 characters and contain uppercase, number, and special character." 20 ] 21 } 22 23 return nil 24}
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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal