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 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 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?

import java.time.LocalDate
import java.time.Period
import java.util.UUID

data class UserData(
    val username: String?,
    val email: String?,
    val password: String?,
    val dateOfBirth: String,
    val address: Address
)

data class Address(
    val street: String?,
    val city: String?,
    val country: String?,
    val postalCode: String?
)

data class RegistrationResponse(
    val success: Boolean,
    val message: String,
    val userId: String?
)

interface IDataStore {
    fun store(userData: UserData)
}

class UserRegistrationService(private val dataStore: IDataStore) {

    fun processUserRegistration(userData: UserData): RegistrationResponse {
        return try {
            // User validation
            if (userData.username.isNullOrBlank() || userData.username.length < 3 || userData.username.length > 20) {
                return RegistrationResponse(false, "Invalid username. Must be between 3 and 20 characters.", null)
            }

            if (userData.email.isNullOrBlank() || !userData.email.contains("@") || !userData.email.contains(".")) {
                return RegistrationResponse(false, "Invalid email format.", null)
            }

            if (userData.password.isNullOrBlank()
                || userData.password.length < 8
                || !userData.password.contains(Regex(".*[A-Z].*"))
                || !userData.password.contains(Regex(".*\\d.*"))
                || !userData.password.contains(Regex(".*[!@#\$%^&*].*"))
            ) {
                return RegistrationResponse(false, "Password must be at least 8 characters and contain uppercase, number, and special character.", null)
            }

            // Date validation
            val birthDate = LocalDate.parse(userData.dateOfBirth)
            val today = LocalDate.now()
            val age = Period.between(birthDate, today)
            if (age.years < 18 || age.years > 120) {
                return RegistrationResponse(false, "Invalid date of birth or user must be 18+", null)
            }

            // Address validation
            val address = userData.address
            if (address.street.isNullOrBlank() || address.street.length < 5) {
                return RegistrationResponse(false, "Invalid street address", null)
            }
            if (address.city.isNullOrBlank() || address.city.length < 2) {
                return RegistrationResponse(false, "Invalid city", null)
            }
            if (address.country.isNullOrBlank() || address.country.length < 2) {
                return RegistrationResponse(false, "Invalid country", null)
            }
            if (address.postalCode.isNullOrBlank() || !address.postalCode.matches(Regex("^[A-Z0-9]{3,10}$"))) {
                return RegistrationResponse(false, "Invalid postal code", null)
            }

            // Data transformation
            val userId = "USER_" + UUID.randomUUID().toString().substring(0, 8)
            val normalizedData = UserData(
                userData.username.toLowerCase(),
                userData.email.toLowerCase(),
                userData.password,
                birthDate.toString(),
                Address(
                    address.street.trim(),
                    address.city.trim(),
                    address.country.toUpperCase(),
                    address.postalCode.toUpperCase()
                )
            )

            dataStore.store(normalizedData)

            RegistrationResponse(true, "User registered successfully", userId)
        } catch (e: Exception) {
            RegistrationResponse(false, "Registration failed: ${e.message}", null)
        }
    }
}

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.

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