最可读的方式来编写简单的条件检查

JRL*_*JRL 6 language-agnostic coding-style conditional-statements

编写多条件检查的最可读/最佳方法是什么,如下所示?

我能想到的两种可能性(这是Java,但语言在这里并不重要):

选项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);
   }
Run Code Online (Sandbox Code Playgroud)

选项2:

   if (passwordField.getPassword().length > 0 &&
         !stationIDTextField.getText().trim().isEmpty() &&
         !userNameTextField.getText().trim().isEmpty() {
      okButton.setEnabled(true);
   }
Run Code Online (Sandbox Code Playgroud)

关于选项2我不喜欢的是线条包裹然后压痕变成了痛苦.关于选项1,我不喜欢的是,它无需创建变量,需要查看两个位置.

所以你怎么看?任何其他的选择吗?

Chr*_*sma 27

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


bool HasPassword() {
 return passwordField.getPassword().length > 0;
}
Run Code Online (Sandbox Code Playgroud)

等等


Tre*_*ent 6

请注意,选项1不允许短路行为.也就是说,在计算第一个条件的结果之前,计算所有条件的值.