编写多个条件检查的最易读/最好的方法是什么,如下面所示?
我可以想到两种可能性(这是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);
}备选方案2:
if (passwordField.getPassword().length > 0 &&
!stationIDTextField.getText().trim().isEmpty() &&
!userNameTextField.getText().trim().isEmpty() {
okButton.setEnabled(true);
}关于选项2,我不喜欢的是,行包装,然后缩进成为痛苦。对于选项1,我不喜欢的是它不需要为任何东西创建变量,并且需要查看两个位置。
你怎么看?还有其他的选项吗?
发布于 2009-04-28 17:05:15
if (HasPassword() && HasStation() && HasUserName())
okButton.setEnabled(true);
bool HasPassword() {
return passwordField.getPassword().length > 0;
}等。
https://stackoverflow.com/questions/798919
复制相似问题