我正在写一些代码,当我觉得丑陋和不雅时,我会感觉到这种感觉,但我无法立即看到避免它的方法.
我有一个json对象,我是从第三方获得的.我知道会发生什么,但我无法确定每个元素肯定会在那里,所以我需要检查它是否存在如下:
if (object.has(ELEMENT)) {
JsonObject element = object.get(ELEMENT);
}
问题是我有时必须深入到对象中,当我得到如此多的嵌套ifs时,它开始变得难看.这是一个例子:
private boolean lineExists(JsonArray orders, Line lineItem) {
final String LINE_ITEMS = "lineItems";
final String ELEMENTS = "elements";
final String NOTE = "note";
boolean exists = false;
log.debug("Checking if line item already exists in order...");
// if there is no order payload then the order hasn't already been posted so there can't be a duplicate line item
if (orders != null) {
for (int i = 0; i < orders.size(); i++) {
JsonObject order = orders.get(i).getAsJsonObject();
if (order.has(LINE_ITEMS)) {
JsonObject lineItems = order.get(LINE_ITEMS).getAsJsonObject();
if (lineItems.has(ELEMENTS)) {
JsonArray elements = lineItems.get(ELEMENTS).getAsJsonArray();
for (int j = 0; j < elements.size(); j++) {
JsonObject existingLine = elements.get(j).getAsJsonObject();
if (existingLine.has(NOTE)) {
String note = existingLine.get(NOTE).getAsString();
// the note may change after this comparison so just check if the ID is contained in the
// note
if (note.contains(lineItem.getNote())) {
exists = true;
log.warn("Line item with note containing '{}' already exists in order.",
lineItem.getNote());
}
}
}
}
}
}
}
return exists;
}
我知道我可以将一些测试分成他们自己的方法,如下所示:
private boolean lineExistCheck(JsonObject order) {
final String LINE_ITEMS = "lineItems";
final String ELEMENTS = "elements";
return order.has(LINE_ITEMS) && order.get(LINE_ITEMS).getAsJsonObject().has(ELEMENTS);
}
我只是想知道是否有一种设计模式或思维方式可以帮助我在这种情况下编写更好的代码.
解决方法:
从本质上讲,这个想法是每个要求你缩进到正确的东西…应该更好地进入自己的方法.因此,您不仅要将测试放在单独的方法中;你走得更远
并注意:使用这样的决赛…不会给你买任何东西.在我看来(但这是对风格的看法!)这只是浪费,使你的CPU燃烧周期没有充分的理由.更进一步;将这些局部常量转换为全局静态值可能更有意义.
另一件事(考虑到你正在研究一个JsonObject,这当然很棘手)……这段代码是Tell Dont Ask的一个“好”的反例.重点是:你的代码是查询其他对象的内部状态;根据这个做出决定.实质上,这是程序编程.在真实的OO中,你不会要求对象获取某些信息然后做某事;不;你只需告诉那个对象做任何需要的事情.但正如所说;这对这里没有帮助;鉴于你正在处理一个通用的JsonObject;而不是一个“真正的”对象,它具有已知且定义明确的界面,您可以用它来“告诉”它该做什么.
标签:java,json,design-patterns
来源: https://codeday.me/bug/20190828/1756805.html