Home > Mobile >  How to split condition in method into two methods with separate condition
How to split condition in method into two methods with separate condition

Time:01-11

I have this code to check if the user is an admin or the owner of the message. I must split this method into two methods: first - check if the user is admin, second - if the user is owner. However, it won't work properly if I just divide the condition into two.

public static void checkIfTheUserIsAdminOrTheOwnerOfTheComment(Comment commentFound, SecurityUser user){
    if (!(commentFound.getAuthor().getId().equals(user.getUserId())
            ||(user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission()))))) {
        throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
    }
}

I tried this

 public static void checkIfTheUserIsTheOwnerOfTheComment(Comment commentFound, SecurityUser user){
    if (!commentFound.getAuthor().getId().equals(user.getUserId())) {
        throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
    }
}


 public static void checkIfTheUserIsAdmin(Comment commentFound, SecurityUser user){
    if (!user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission())))) {
        throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
    }
}

But it won't work okay because if I log in as an admin I will have an exception that I'm not the owner, but I MUST divide this into two separate methods. Any suggestions?

CodePudding user response:

One way to refactor would be to extract separate methods that perform each check. Perhaps still not perfect, but it would look something like this:

  1. First check:
private boolean checkIsUserOwnerOfComment(Comment commentFound, SecurityUser user) {
    return commentFound.getAuthor().getId().equals(user.getUserId());
}
  1. Second check:
private boolean checkIsUserAdmin(Comment commentFound, SecurityUser user) {
    return user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission()));
}

And finally, perform both checks and raise the exception according to any logic that's relevant to your use case.

public static void validateUser(Comment commentFound, SecurityUser user){
    boolean userIsAdminOrOwnerOfComment = this.checkIsUserAdmin(commentFound, user) || this.checkIsUserOwnerOfComment(commentFound, user);
    if (!userIsAdminOrOwnerOfComment) {
        throw new ForbiddenRequestException(Errors.ERROR4.getMessage());
    }
}
  •  Tags:  
  • Related