gpt4 book ai didi

java - 避免使用 if 对于链式对象

转载 作者:行者123 更新时间:2023-12-01 19:28:51 24 4
gpt4 key购买 nike

我有一个像这样的复杂对象;

Object A
Object B
Object C
Object D
property A
property B

因此,如果我需要在我的 View 中显示属性 A,我需要

  A.getB().getC().getD().getPropertyA();

但是如果我的用户不发送对象 C 怎么办?

所以我需要为每个对象创建一个 If

if(A.getB() != null){
if(A.getB().getC() != null){
if(A.getB().getC().getD() != null){
//here I can show the propertyA
}
}
}

现在我必须在 3 个 View 中显示此属性

有更好的方法吗?一个框架或类似的东西来解决这个问题?

最佳答案

您可以使用Optional.ofNullablemap:

Optional.ofNullable(A.GetB())
.map(B::getC)
.map(C::getD)
.map(D::getPropertyA)
.orElseThrow()

P.S.1:一些开发人员(和 linter)发现这种方法有代码味道,但我认为这样更具可读性。

P.S.2:您可以使用 .orElse 代替 .orElseThrow 的默认值。

关于java - 避免使用 if 对于链式对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60419098/

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