编写多个条件检查的最易读/最好的方法是什么,如下面所示?
我可以想到两种可能性(这是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;
}等。
发布于 2009-04-28 17:09:12
注意,选项1不允许短路行为。也就是说,在计算第一个条件的结果之前,计算所有条件项的值。
发布于 2009-04-28 17:03:24
我会修改选项1,使您使用的变量名称实际上有意义。也就是说,将"c2“的名称更改为类似于"stationIDIsEmpty”的名称(并将NOT移到条件中)。这样,条件是可读的,而不必来回浏览每个变量。
所以我的代码看起来可能是:
boolean enteredPassword = passwordField.getPassword().length > 0;
boolean stationIDIsEmpty = stationIDTextField.getText().trim().isEmpty();
boolean userNameIsEmpty = userNameTextField.getText().trim().isEmpty();
if (enteredPassword && !stationIDIsEmpty && !userNameIsEmpty) {
okButton.setEnabled(true);
}https://stackoverflow.com/questions/798919
复制相似问题