链接Optional.orElseThrow

时间:2019-02-26 15:44:40

标签: java functional-programming optional

我有一段这样的代码:

Sub Test()

Dim Cell as Range
Dim NameCell as Range
Dim myRow as Long

myRow = 2
With Sheets("Raw Data")
    For each NameCell in Worksheet("myNames").Range("A1:A10)
        For Each Cell In .Range("C1:C" & .Cells(.Rows.Count, "C").End(xlUp).Row)
            If Cell.Value = "Assigned" and Cell.Offset(0,1).Value = NameCell.Value Then
                .Rows(Cell.Row).copy Destination:=Sheets("WIP").Rows(myRow)
                myRow = myRow + 1
                Exit For
            End If
        Next Cell
    Next NameCell
End With

End Sub

此刻,当给定的return getObject() .map(obj -> obj.getNullableField()) .orElseThrow(() -> new IllegalStateException("Object not found!")); 不存在时,我抛出异常。

现在,我还需要检查Object中的nullableField是否存在。

一个明显的解决方案可能是这样的:

Object

但我想在同一功能链中实现此目标...

我想念什么?

3 个答案:

答案 0 :(得分:8)

它可以直接在同一链中实现,您将抛出不同的异常。现在,它的可读性比第一个解决方案还差,因此您需要权衡取舍。

return getObject().map(obj -> Optional.ofNullable(obj.getNullableField())
                                      .orElseThrow(() -> new IllegalStateException("Field is not present")))
                  .orElseThrow(() -> new IllegalStateException("Object not found!"));

答案 1 :(得分:4)

与其建议嵌套,不如建议一个简单的序列来解决该问题:

var value = getObject()
        .orElseThrow(() -> new IllegalStateException("Object not found!"));

return Optional.of(value) // ensured value check already
        .map(CustomObject::getNullableField) // takes care ofNullable
        .orElseThrow(() -> new IllegalStateException("Field is not present"));

答案 2 :(得分:0)

我建议完全放弃Optional方法,或者至少仅在开始时使用它(假设getObject()无法更改):

var value = getObject()
    .orElseThrow(() -> new IllegalStateException("Object not found!"));

var field = value.getNullableField();
if(field == null) {
    throw new IllegalStateException("Field is not present");
}
return field;

这并没有引入新的Optional包装器,因此您可以“流利”并在一行/语句中完成所有操作。