Grails 如果不是,则条件不';I don’我没有按预期工作

Grails 如果不是,则条件不';I don’我没有按预期工作,grails,groovy,boolean-logic,demorgans-law,Grails,Groovy,Boolean Logic,Demorgans Law,我写了一个if-else条件,它利用if-not(!)抛出一个错误。但是,该条件的行为与我预期的不同,无论当前用户是谁,都会抛出错误: public void findCorrectUserRole() { if (Book.name.equals("Test Answers")) { User currentUser = User.getCurrentUser() if (currentUser) { if (!currentUs

我写了一个if-else条件,它利用if-not(!)抛出一个错误。但是,该条件的行为与我预期的不同,无论当前用户是谁,都会抛出错误:

public void findCorrectUserRole() {
    if (Book.name.equals("Test Answers")) {
        User currentUser = User.getCurrentUser()
        if (currentUser) {
            if (!currentUser.hasUserRole("Teacher") || !currentUser.hasUserRole("System Administrator")) {
                throw new LCEX("Sorry, only a teacher or System Administrator can edit this.");
            }
        }
    }else{
        "Do Something Else"
    }
}

你做了一个无效的假设,即逻辑not运算符处理逻辑运算的方式与代数中负号的工作方式相同。有一个名为的规则可以帮助您安全地转换逻辑表达式

在编写代码时,用户只有一种方法可以避免此异常,用户必须同时具有教师和系统管理员角色:

groovy:000> a = true; b = false; !a || !b // only one is true -> true
===> true
groovy:000> a = b = false; !a || !b  // neither is true -> true
===> true
groovy:000> a = b = true; !a || !b  // both are true -> false
===> false
如果使用DeMorgan定律重写,这一点可能会更清楚(将否定从parens内部带出意味着操作符必须从
|
更改为
&&
);您的代码与此等效:

if (!(currentUser.hasUserRole("Teacher") 
&& currentUser.hasUserRole("System Administrator"))) {
“当前用户并非同时具有教师角色和系统管理员角色”

这绝对不是你想要的。你想要的是

if (!currentUser.hasUserRole("Teacher") 
&& !currentUser.hasUserRole("System Administrator")) {
“当前用户没有教师角色,也没有系统管理员角色”

等价地,你可以把它写成

if (!(currentUser.hasRole("Teacher") 
|| currentUser.hasRole("System Administrator"))) {
“当前用户不是教师或系统管理员”

是:

“not(A和B)”与“(not A)或(not B)”相同

“not(A或B)”与“(not A)and(not B)”相同


如果您的情况不正确,则应为:

if (!currentUser.hasUserRole("Teacher") && !currentUser.hasUserRole("System Administrator")) {
            throw new LCEX("Sorry, only a teacher or System Administrator can edit this.");
          }


现在,如果当前用户角色是“教师”,则他不是“系统管理员”,因此if条件为真。

每次我在工作中进行代码复查时,我都必须解释DeMorgan定律。:)
if (!(currentUser.hasUserRole("Teacher") || currentUser.hasUserRole("System Administrator"))) {
            throw new LCEX("Sorry, only a teacher or System Administrator can edit this.");
          }