What would be the most readable/best way to write a multiple conditional check such as shown below?
Two possibilities that I could think of (this is Java but the language really doesn't matter here):
Option 1:
boolean c1 = passwordField.getPassword().length > 0;
boolean c2 = !stationIDTextField.getText().trim().isEmpty();
boolean c3 = !userNameTextField.getText().trim().isEmpty();
if (c1 && c2 && c3) {
okButton.setEnabled(true);
}
Option 2:
if (passwordField.getPassword().length > 0 &&
!stationIDTextField.getText().trim().isEmpty() &&
!userNameTextField.getText().trim().isEmpty() {
okButton.setEnabled(true);
}
What I don't like about option 2 is that the line wraps and then indentation becomes a pain. What I don't like about option 1 is that it creates variables for nothing and requires looking at two places.
So what do you think? Any other options?
A statement written in the if-then form is a conditional statement. “if p then q .” Example 1: If two angles are adjacent , then they have a common side.
The most commonly used conditional statement is if . Whenever you see an if statement, read it as 'If X is TRUE, do a thing'. Including an else statement simply extends the logic to 'If X is TRUE, do a thing, or else do something different'.
A conditional statement has two parts: hypothesis (if) and conclusion (then). In fact, conditional statements are nothing more than “If-Then” statements! Sometimes a picture helps form our hypothesis or conclusion.
if (HasPassword() && HasStation() && HasUserName())
okButton.setEnabled(true);
bool HasPassword() {
return passwordField.getPassword().length > 0;
}
etc.
Note that option 1 does not allow for short circuiting behavior. That is, you calculate the value of all of the conditionals before evaluating the result of the first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With