gpt4 book ai didi

java - 对方法的多个参数进行 null 检查的优雅或惯用的方式

转载 作者:行者123 更新时间:2023-12-01 22:38:58 25 4
gpt4 key购买 nike

我有一个如下所示的方法,用于创建 POJO 并使用所述 POJO 的字段填充父对象

public void createMyPOJO(
ParentObject parentObject,
Boolean i,
Boolean j,
Boolean k) {
if (i != null || j != null || k != null) {
MyPojo myPojo = new MyPojo();
if (i != null) myPojo.setIndicatorI(i);
if (j != null) myPojo.setIndicatorJ(j);
if (k != null) myPojo.setIndicatorK(k);

parentObject.setMyPojo(myPojo);
}
}

使用可选类型或 @Nullable 只会让这个变得困惑,并且使用像 Boolean[] 这样的数据类型也感觉不到太大的改进。什么是更惯用或更优雅的方法来避免基本上每一行都进行空检查?

最佳答案

您可以使用 boolean 而不是 Boolean 并让 autoboxing为您完成这项工作(在调用 createMyPOJO(...) 时使用 false 而不是 null)。这也删除了空检查验证。

public void createMyPOJO(
ParentObject parentObject,
boolean i,
boolean j,
boolean k) {
if (i || j || k) {
MyPojo myPojo = new MyPojo();
if(i) myPojo.setIndicatorI(i);
if(j) myPojo.setIndicatorJ(j);
if(k) myPojo.setIndicatorK(k);

parentObject.setMyPojo(myPojo);
}
}

您可以选择添加 builderMyPojo 类并使用它来构建 MyPojo 的新实例。

编辑:

随着需求的增长,每个指标都应该支持 nulltruefalse 值,我认为最好的解决方案是使用构建器。

public class MyPojoBuilder {

private Boolean indicatorI;
private Boolean indicatorJ;
private Boolean indicatorK;
private ParentObject parentObject;

private MyPojoBuilder(ParentObject parentObject) {
this.parentObject = parentObject;
}

public static MyPojoBuilder withParentObject(ParentObject parentObject) {
return new MyPojoBuilder(parentObject);
}

public MyPojoBuilder withIndicatorI(Boolean value) {
indicatorI = value;
return this;
}

public MyPojoBuilder withIndicatorJ(Boolean value) {
indicatorJ = value;
return this;
}

public MyPojoBuilder withIndicatorK(Boolean value) {
indicatorK = value;
return this;
}

public void build() {
if (indicatorI == null && indicatorJ == null && indicatorK == null) {
// Throw some exception instead???
return;
}

if (parentObject == null) {
throw new IllegalStateException("ParentObject cannot be null");
}

MyPojo myPojo = new MyPojo();
myPojo.setIndicatorI(indicatorI);
myPojo.setIndicatorJ(indicatorJ);
myPojo.setIndicatorK(indicatorK);

parentObject.setMyPojo(myPojo);
}
}

如果需要,可以扩展构建器以创建并返回新的 ParentObject 实例。

使用示例

ParentObject parentObjectWithIndicatorIAndK = new ParentObject();

MyPojoBuilder.withParentObject(parentObjectWithIndicatorIAndK)
.withIndicatorI(true)
.withIndicatorK(false)
.build();

System.out.println(parentObjectWithIndicatorIAndK);

输出:

ParentObject{myPojo=MyPojo{indicatorI=true, indicatorJ=null, indicatorK=false}}

这是一个demo project实现这一概念。

关于java - 对方法的多个参数进行 null 检查的优雅或惯用的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58509357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com