Refactoring Long Methods with the Extract Method Technique

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?

public class UserRegistrationService {
    private final IDataStore dataStore;

    public UserRegistrationService(IDataStore dataStore) {
        this.dataStore = dataStore;
    }

    public RegistrationResponse processUserRegistration(UserData userData) {
        try {
            // User validation
            if (userData.getUsername() == null || userData.getUsername().isBlank()
                || userData.getUsername().length() < 3 || userData.getUsername().length() > 20) {
                return new RegistrationResponse(false, "Invalid username. Must be between 3 and 20 characters.", null);
            }

            if (userData.getEmail() == null || userData.getEmail().isBlank()
                || !userData.getEmail().contains("@") || !userData.getEmail().contains(".")) {
                return new RegistrationResponse(false, "Invalid email format.", null);
            }

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

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

            // Address validation
            Address address = userData.getAddress();
            if (address.getStreet() == null || address.getStreet().isBlank() || address.getStreet().length() < 5) {
                return new RegistrationResponse(false, "Invalid street address", null);
            }
            if (address.getCity() == null || address.getCity().isBlank() || address.getCity().length() < 2) {
                return new RegistrationResponse(false, "Invalid city", null);
            }
            if (address.getCountry() == null || address.getCountry().isBlank() || address.getCountry().length() < 2) {
                return new RegistrationResponse(false, "Invalid country", null);
            }
            if (address.getPostalCode() == null || address.getPostalCode().isBlank()
                || !address.getPostalCode().matches("^[A-Z0-9]{3,10}$")) {
                return new RegistrationResponse(false, "Invalid postal code", null);
            }

            // Data transformation
            String userId = "USER_" + UUID.randomUUID().toString().substring(0, 8);
            UserData normalizedData = new UserData(
                userData.getUsername().toLowerCase(),
                userData.getEmail().toLowerCase(),
                userData.getPassword(),
                birthDate.toString(),
                new Address(
                    address.getStreet().trim(),
                    address.getCity().trim(),
                    address.getCountry().toUpperCase(),
                    address.getPostalCode().toUpperCase()
                )
            );

            dataStore.store(normalizedData);

            return new RegistrationResponse(true, "User registered successfully", userId);
        } catch (Exception e) {
            return new RegistrationResponse(false, "Registration failed: " + e.getMessage(), "");
        }
    }
}

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