Skip to main content
3 of 3
added 529 characters in body
K.H.
  • 2.7k
  • 7
  • 25

You can just extract those first 2 if's into separate methods (or single method), returning the user at the same time. Something like getDisabledUserOrThrow() (Returning the AppUser instance, not Optional, because either you return a "valid" user (no-enabled) or throw your exception).

You can use that anywhere you need to ensure you have user instance. Something like this:

private AppUser getDisabledUserOrThrow(String email) throws VerificationTokenException {
    Optional<AppUser> optionalUser = appUserService.findByEmail(email);
    if (optionalUser.isEmpty()) {
        throw new VerificationTokenException(HttpStatus.UNAUTHORIZED, "Email not found");
    }

    AppUser user = optionalUser.get();
    if (user.isEnabled()) {
        throw new VerificationTokenException(HttpStatus.FORBIDDEN, "Something went wrong");
    }
    return user;
}

You could do the same to get the token if that's what is the most common data necessary for your logic further.

Edit:

To expand on positioning this method:

  • One way would be to put it in your parent controller (if you have one) as protected methods so that you can call them directly from your controller.
  • I am also thinking - if those methods are basically getting your domain models, you can look at those as methods of Repositories (look up this pattern if needed) and inject them into your controllers :-)
  • It's always possible to create static methods instead, which is also fine if there's no clear place of putting it.
K.H.
  • 2.7k
  • 7
  • 25