Live Refactor: Turning a Messy Java Registration Method into Intent‑Clear Code
The article demonstrates how a convoluted Java user‑registration method—filled with magic error codes, inline regex checks, deep nesting, and mutable parameters—can be systematically refactored by introducing meaningful exception types, extracting password validation, applying early‑return style, and using immutable request records to produce clear, intent‑driven code.
Running code does not guarantee readability; after months the original implementation becomes hard to follow. The article uses a typical user‑registration method to illustrate common readability problems and shows step‑by‑step improvements using Java 17.
Give errors meaningful names
The original method throws RuntimeException with magic strings such as "u105" and "u212", which convey no meaning to readers.
public User registerUser(User user) {
if (!validateUserInput(user)) {
throw new RuntimeException("u105");
}
Pattern[] rules = {
Pattern.compile("[a-z]"), Pattern.compile("[A-Z]"),
Pattern.compile("[0-9]"), Pattern.compile("[^a-zA-Z0-9]")
};
if (user.getPassword().length() >= 8 &&
Arrays.stream(rules).allMatch(r -> r.matcher(user.getPassword()).find())) {
if (userRepository.findByEmail(user.getEmail()) != null) {
throw new RuntimeException("u212");
}
} else {
throw new RuntimeException("u201");
}
user.setPassword(passwordEncoder.encode(user.getPassword()));
return userRepository.save(user);
}Introducing a custom BizException that carries an error code and a readable message makes the intent explicit:
throw new BizException("InvalidParam", "输入不合法");
throw new BizException("UserAlreadyExists", "邮箱已被注册");Hide implementation details
The password‑validation logic is tangled with business flow. Extracting it into a dedicated method isolates the regex details.
private static final List<Pattern> PASSWORD_RULES = List.of(
Pattern.compile("[a-z]"),
Pattern.compile("[A-Z]"),
Pattern.compile("[0-9]"),
Pattern.compile("[^a-zA-Z0-9]")
);
private boolean isPasswordStrong(String password) {
return password.length() >= 8 &&
PASSWORD_RULES.stream().allMatch(r -> r.matcher(password).find());
}Calling isPasswordStrong(password) clearly signals the intent without exposing regex internals.
Make code read top‑to‑bottom
Deep nesting forces readers to jump between indentation levels. Using early‑return (or early‑throw) turns the method into a straight line of independent checks.
Validate input first.
Validate password next.
Check email uniqueness.
Finally save the user.
Avoid silently mutating parameters
Modifying the passed‑in User object hides side effects from callers. Java 17’s record type provides an immutable request carrier.
public record UserRegistrationRequest(
String username,
String email,
String password
) {}Because a record has no setters, the method cannot alter the caller’s data.
Summary
After applying the refactorings, the method becomes concise and expressive:
public User registerUser(UserRegistrationRequest request) {
if (!validateUserInput(request)) {
throw new BizException("InvalidParam", "输入不合法");
}
if (!isPasswordStrong(request.password())) {
throw new BizException("InvalidPassword", "需包含大小写字母、数字和特殊字符,且不少于8位");
}
if (userRepository.findByEmail(request.email()) != null) {
throw new BizException("UserAlreadyExists", "邮箱已被注册");
}
return userRepository.save(new User(
request.username(),
request.email(),
passwordEncoder.encode(request.password())));
}Highlighting code clarity is an effective way to control complexity.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
samdeepthink
Knowledge Planet: Old Dock's Tech Chronicles Zhihu: SamDeepThinking A technical manager who still codes heavily on the front line. From junior developer to tech lead, then tech manager, now leading the whole front‑ and back‑end development team—leveling up along the way. I have some insights on programming, career development, and tech management.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
