因为我找不到一个和我的结构相似的问题,所以我要问它。
我有以下代码:
for (Object o : array1) {
for (Object o2 : array2) {
if (condition1) {
//get a variable for condition2 (depends on iteration elements)
if (condition2) {
if (condition3) {
//do something
} else if (condition4) {
//do something
}
}
}
}
}
我也可以把它写成
for (Object o : array1) {
for (Object o2 : array2) {
if (condition1 && condition3) {
// get a variable for condition2 (depends on iteration elements)
if (condition2) {
// do something
}
} else if (condition1 && condition4) {
// get a variable for condition2
if (condition2) {
// do something
}
}
}
}
这也会起到同样的作用。在第一个示例中,我试图尽可能多地使用代码,在第二个示例中,我必须多次使用相同的代码。
现在我读
on this question
,如果可能的话,应该避免嵌套。然而,在我的理解中,在第一个例子中,多次使用相同的代码是更干净的。
我的问题是,是否应该避免多次使用同一代码的成本?
我在这里询问的是最佳实践/标准,而不是意见。
我知道我可以把它移到一个单独的方法,但最后我可能会有同样数量的代码。
编辑:
在Lino的回答和评论的帮助下,我提出了以下构想:
for (Object o : array1) {
// get a variable for condition2 (depends on iteration elements)
if (condition2) {
for (Object o2 : array2) {
if (condition1) {
if (condition3) {
// do something
} else if (condition4) {
// do something
}
}
}
}
}