gpt4 book ai didi

java - 如何以 Java 8 函数式风格重写仅一个变量类型不同的两个代码分支?

转载 作者:行者123 更新时间:2023-12-01 19:53:42 25 4
gpt4 key购买 nike

我想以函数式风格重写以下逻辑,即使用 mapfilterifPresent 编写单行逻辑orElseorElseGetorElseThrow

String id;
if (entity.legacyIndicator().isPresent()) { // field is an Optional<Foo>
if (entity.legacyId().isPresent()) { // field is an Optional<Long>
id = entity.legacyId().toString(); // e.g. id = '01234567'
} else {
throw new IOException("No ID found.");
}
} else {
if (entity.newId().isPresent()) { // field is an Optional<UUID>
id = entity.newId().toString(); // e.g. id = '01234567-89ab-cdef-0123-456789abcdef'
} else {
throw new IOException("No ID found.");
}
}

对我来说主要的麻烦是 legacyId()newId() 是不同的类型。作为程序员,我知道它们都共享 isPresent()toString(),但不共享实际的接口(interface),那么如何“统一”这两个分支?

我很快就会尽最大努力编辑这个问题,因为我仍在尽我所能。但我对统一分支完全感到困惑。

最佳答案

好吧,不是很干净,但我会选择类似的东西

    public String getId(Test.Entity entity) throws Throwable {
return entity.legacyIndicator()
.map(o -> (Optional) entity.legacyId())
.orElseGet(() -> (Optional) entity.newId())
.orElseThrow(() -> new IOException("No ID found."))
.toString();
}

这里有一些 Junit 测试来验证执行

@org.junit.Test
public void test() throws Throwable {
Entity entity = new Entity();

entity.legacyIndicator = Optional.empty();
final UUID uuid = UUID.randomUUID();
entity.newId = Optional.of(uuid);

String id = getId(entity);
Assert.assertEquals(uuid.toString(), id);


entity = new Entity();

entity.legacyIndicator = Optional.of(Boolean.TRUE);
entity.newId = Optional.of(uuid);
entity.legacyId = Optional.of("SomeId");
id = getId(entity);

Assert.assertEquals("SomeId", id);
}

@org.junit.Test(expected = IOException.class)
public void testExceptionLegacy() throws Throwable {
Entity entity = new Entity();

entity.legacyIndicator = Optional.of(Boolean.TRUE);
entity.legacyId = Optional.empty();
String id = getId(entity);
}

@org.junit.Test(expected = IOException.class)
public void testExceptionNew() throws Throwable {
Entity entity = new Entity();

entity.legacyIndicator = Optional.empty();
entity.legacyId = Optional.empty();
entity.newId = Optional.empty();
String id = getId(entity);
}

class Entity {
Optional<Boolean> legacyIndicator;
Optional<String> legacyId;
Optional<UUID> newId;

Optional<Boolean> legacyIndicator() {
return legacyIndicator;
}

Optional<UUID> newId() {
return newId;
}

Optional<String> legacyId() {
return legacyId;
}

}

关于java - 如何以 Java 8 函数式风格重写仅一个变量类型不同的两个代码分支?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50365506/

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