【问题标题】:How to split condition in method into two methods with separate condition如何将方法中的条件拆分为具有单独条件的两个方法
【发布时间】:2022-01-05 15:33:37
【问题描述】:

我有这个代码来检查用户是管理员还是消息的所有者。我必须将此方法拆分为两种方法:第一个 - 检查用户是否为管理员,第二个 - 用户是否为所有者。但是,如果我只是将条件一分为二,它将无法正常工作。

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());
    }
}

我试过了

 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());
    }
}

但它不能正常工作,因为如果我以管理员身份登录,我会遇到我不是所有者的异常,但我必须将它分成两个单独的方法。有什么建议吗?

【问题讨论】:

  • 我在 CommentService 类中写了这个表达式,checkIfTheUserIsAdmin(commentFound, user); checkIfTheUserIsTheOwner(commentFound, user);
  • 我还是不知道你写了什么或者你是怎么写的。请将该代码添加到您的问题中,而不是对其进行描述。

标签: java spring if-statement exception


【解决方案1】:

重构的一种方法是提取执行每个检查的单独方法。也许仍然不完美,但它看起来像这样:

  1. 第一次检查:
private boolean checkIsUserOwnerOfComment(Comment commentFound, SecurityUser user) {
    return commentFound.getAuthor().getId().equals(user.getUserId());
}
  1. 第二次检查:
private boolean checkIsUserAdmin(Comment commentFound, SecurityUser user) {
    return user.getAuthorities().contains(new SimpleGrantedAuthority(Authorities.ADMIN_WRITE.getPermission()));
}

最后,根据与您的用例相关的任何逻辑执行这两项检查并引发异常。

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());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多