我想清理一些令我头疼的代码:
activityStandardAttributeValue
.setProduct((standardAttributeForm != null && standardAttributeForm
.getProduct() != null) ? standardAttributeForm
.getProduct()
: (groupedStandardAttributeForm != null ? groupedStandardAttributeForm
.getProduct() : null));
activityStandardAttributeValue
.setProject((standardAttributeForm != null && standardAttributeForm
.getProject() != null) ? standardAttributeForm
.getProject()
: (groupedStandardAttributeForm != null ? groupedStandardAttributeForm
.getProject() : null));
我可以简单地将其更改为更容易阅读的形式,如:
Product product = null;
if(standardAttributeForm != null && standardAttributeForm.getProduct() != null) {
product = standardAttributeForm.getProduct();
} else if (groupedStandardAttributeForm != null && groupedStandardAttributeForm.getProduct() != null) {
product = groupedStandardAttributeForm.getProduct();
}
activityStandardAttributeValue.setProduct(product);
Project project = null;
if(standardAttributeForm != null && standardAttributeForm.getProduct() != null) {
project = standardAttributeForm.getProject();
} else if (groupedStandardAttributeForm != null && groupedStandardAttributeForm.getProject() != null) {
project = groupedStandardAttributeForm.getProject();
}
问题在于,对于不同的属性,这个相同的基本逻辑重复大约16次,并且它不是更清洁。我想创建一个通用的方法来做到这一点,而不必重复相同的基本逻辑。棘手的部分是standartAtributeForm或groupedStandardAttributeForm可能为null。
感谢任何帮助。
答案 0 :(得分:3)
这不是一个真正的答案,但它太大了,无法发表评论(并依赖于格式):
只需使用更好的格式即可轻松阅读。以下是您通过google-java-format传递的代码:
activityStandardAttributeValue.setProduct(
(standardAttributeForm != null && standardAttributeForm.getProduct() != null)
? standardAttributeForm.getProduct()
: (groupedStandardAttributeForm != null
? groupedStandardAttributeForm.getProduct()
: null));
activityStandardAttributeValue.setProject(
(standardAttributeForm != null && standardAttributeForm.getProject() != null)
? standardAttributeForm.getProject()
: (groupedStandardAttributeForm != null
? groupedStandardAttributeForm.getProject()
: null));
我想你可以这样做:
<T> getThing(Function<Form, T> extractor, T... forms) {
for (T form : forms) {
if (form != null) {
T thing = extractor.apply(form);
if (thing != null) return thing;
}
}
return null;
}
然后:
activityStandardAttributeValue.setProduct(
getThing(Form::getProduct, standardAttributeForm, groupedStandardAttributeForm));
activityStandardAttributeValue.setProject(
getThing(Form::getProject, standardAttributeForm, groupedStandardAttributeForm));