Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most readable way to write simple conditional check

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?

like image 319
JRL Avatar asked Apr 28 '09 17:04

JRL


People also ask

How do you write conditional statement?

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.

What is the most basic conditional statement?

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'.

What is a simple conditional statement?

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.


2 Answers

if (HasPassword() && HasStation() && HasUserName())
  okButton.setEnabled(true);


bool HasPassword() {
 return passwordField.getPassword().length > 0;
}

etc.

like image 64
Chris Brandsma Avatar answered Oct 16 '22 06:10

Chris Brandsma


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.

like image 40
Trent Avatar answered Oct 16 '22 06:10

Trent