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

后端 未结 11 687
没有蜡笔的小新
没有蜡笔的小新 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.

提交回复
热议问题