如何避免使用Java中的多个语句?
如何重构此方法?
public String getFirstOrLastNameOrBoth() {
if (this.getFirstname() != null && this.getLastname() != null) {
return this.getFirstname() + this.getLastname();
} else if (this.getFirstname() != null && this.getLastname() == null){
return this.getFirstname();
} else if (this.getLastname() != null && this.getFirstname() == null){
return this.getLastname();
}
return 0.0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为了访问字段,无需在班级中调用Getter。改用字段名称。
您可以使用对象> objects 实用程序类的nearnonnnullse(t,t)“ rel =“ nofollow noreferrer”>
noneNulloreLse()
静态方法。There's no need to invoke getter in the class in order to access a field. Use the field name instead.
Instead of null-checks, you can make use of
noneNullOrElse()
static method of theObjects
utility class.strimutils.trimtoempty()
来自Apache Commonsorg.apache.commons.lang3
可以在此处使用this
if it is not necessary.StringUtils.trimToEmpty()
from Apache Commonsorg.apache.commons.lang3
can be used here您可以做的另一件事是在获取方法中传输IF语句,因此您可以在此检查是否有空。更具体地说:
这种方式称为提取方法,在这种情况下,您不仅可以在最后一个方法中而且在Getters中检查NULL。因此,我认为这是安全的。我还使用了Trim方法来删除开头的空格,以防名字为null。
Another thing you can do is to transfer the if statements in the get methods, so you can check there whether something is null or not. More specifically:
This way is called the extract method and in this case, you'll be able to check for null not only in the last method but also in the getters. Therefore I think it is safe. I have also used the trim method in order to remove the spaces in the beginning in case the first name is null.