grailsgroovyboolean-logicdemorgans-law

If not condition doesn't work as expected


I have written an if else condition which makes use of if not(!) to throw an error. However, the condition does not behave how I had expected and the error gets thrown regardless of who is the currentUser:

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"
    }
}

Solution

  • Your if condition is wrong it should be:

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

    or

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

    right now if the currentUser role is "teacher", he is not a "system administrator" so the if condition would be true.