我的应用程序中目前有这样的代码,它非常丑陋,但我不确定重构它的最佳方法是什么,使其稍微不那么冗长。
所以,我有这样的东西:
JsonObject a; // initialized from some nested XML
if (a != null) {
JsonObject b = a.getJsonObject("b");
if (b != null) {
JsonObject c = b.getJsonObject("c");
if (c != null) {
JsonObject d = c.getJsonObject("d");
if (d != null) {
// update d here
//...
// Update c with the updated d
c.put("d", d);
}
}
}
}
这显然很难看,我想知道是否有一种方法可以重构它,使其更直接,嵌套更少。
好的,管理为:
Optional.ofNullable(a)
.map(e -> e.getJsonObject("b"))
.map(e -> e.getJsonObject("c"))
.map(e -> e.getJsonObject("d"))
.ifPresent(e -> {
// Do something
});