Video in progress
Why is a very long method a problem, and how do you break it into pieces?
A long method mixes several jobs: it is hard to read, test and change safely. Pull the logical pieces out into small methods with meaningful names ("Extract Method"), so the main method reads like a list of steps.
📖 Answer
For example, a 150-line register method: validation, password hashing, writing to the database, email, audit log, all in one place with tangled ifs.
After refactoring:
public User register(RegisterRequest req) {
validate(req);
User user = createUser(req);
userRepository.save(user);
welcomeMailer.send(user);
auditLog.userRegistered(user);
return user;
}
Now someone reading the method understands what is going on in 5 seconds, and if they need the details, they step into the method they want.
How to split it:
- Find the blocks inside the method separated by a blank line or a comment; they are ready candidates.
- Use Refactor → Extract Method in the IDE (Ctrl+Alt+M / Cmd+Opt+M in IntelliJ); it is safer than copying by hand.
- Give each new method a name that says what it does.
- Check that tests exist before refactoring.
There is no hard limit, but if a method doesn't fit on the screen or has more than 3 levels of nested if/for, it is time to split it.
Sign up to mark studied questions and save your progress.