What are the cases in which it is better to use unconditional AND (& instead of &&)

后端 未结 11 665
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 10:33

I\'d like to know some cases in Java (or more generally: in programming) when it is preferred in boolean expressions to use the unconditional AND (&

相关标签:
11条回答
  • 2020-11-28 10:53

    Input validation is one possible case. You typically want to report all the errors in a form to the user in a single pass instead of stopping after the first one and forcing them to click submit repeatedly and only get a single error each time:

    public boolean validateField(string userInput, string paramName) {
       bool valid;
       //do validation 
    
       if (valid) {
           //updates UI to remove error indicator (if present)
           reportValid(paramName);   
       } else {
           //updates UI to indicate a problem (color change, error icon, etc) 
           reportInvalid(paramName);  
       }      
    }
    
    public boolean validateAllInput(...) {
    
       boolean valid = true;
       valid = valid & validateField(userInput1, paramName1);
       valid = valid & validateField(userInput2, paramName2);
       valid = valid & validateField(userInput3, paramName3);
       valid = valid & validateField(userInput4, paramName4);
       valid = valid & validateField(userInput5, paramName5);
    
       return valid;
    }
    
    public void onSubmit() {
    
       if (validateAllInput(...)) {
           //go to next page of wizard, update database, etc
           processUserInput(userInput1, userInput2, ... );
       } 
    
    }
    
    public void onInput1Changed() {
       validateField(input1.Text, paramName1);
    }
    
    
    public void onInput2Changed() {
       validateField(input2.Text, paramName2);
    }
    
    ...
    

    Granted, you could trivially avoid the need for short circuit evaluation in validateAllInput() by refactoring the if (valid) { reportValid() ... logic outside of validateField(); but then you'd need to call the extracted code every time validateField() was called; at a minimum adding 10 extra lines for method calls. As always it's a case of which tradeoff's work best for you.

    0 讨论(0)
  • 2020-11-28 10:53

    Short-circuiting can lead to errors in branch prediction on modern processors, and dramatically reduce performance (a notable example is highly optimized ray with axis aligned box intersection code in ray tracing)[clarification needed].

    0 讨论(0)
  • 2020-11-28 10:55

    The only benefit I can think of is when you need to invoke a method or execute a code, no matter the first expression is evaluated to true or false:

    public boolean update()
    {
        // do whatever you want here
        return true;
    }
    
    // ...
    
    if(x == y & update()){ /* ... */}
    

    Although you can do this without &:

    if(x == y){/* ... */}
    update();
    
    0 讨论(0)
  • 2020-11-28 10:58

    If the expression are trivial, you may get a micro-optimisation by using & or | in that you are preventing a branch. ie.

    if(a && b) { }
    if(!(a || b)) { }
    

    is the same as

    if (a) if (b) { }
    if (!a) if (!b) { }
    

    which has two places a branch can occur.

    However using an unconditional & or |, there can be only one branch.

    Whetehr this helps or not is highly dependant on what the code is doing.

    If you use this, I sugegst commenting it to make it very clear why it has been done.

    0 讨论(0)
  • 2020-11-28 11:00

    The && allows the jvm to do short circuit evaluation. That is, if the first argument is false, then it doesn't need to bother checking the second argument.

    A single & will run both sides regardless.

    So, as a contrived example, you might have:

    if (account.isAllowed() & logAccountAndCheckFlag(account))
        // Do something
    

    In that example, you might always want to log the fact that the owner of the account attempted to do something.

    I don't think I have ever used a single & in commercial programming though.

    0 讨论(0)
提交回复
热议问题