下面的帖子将是一个高级花括号讨论,没有对与错的答案,只是更多的“品味”。 它是关于是否将“ else”(以及其他关键字,例如“ catch”,“ finally”)放在换行符上。
有些人可能会写
if (something) {doIt();
} else {dontDoIt();
}
但是,我更喜欢
if (something) {doIt();
}
else {dontDoIt();
}
这看起来很愚蠢。 但是评论呢? 他们去哪里? 这在我看来有点不对劲:
// This is the case when something happens and blah
// blah blah, and then, etc...
if (something) {doIt();
} else {// This happens only 10% of the time, and then you// better think twice about not doing itdontDoIt();
}
以下不是更好吗?
// This is the case when something happens and blah
// blah blah, and then, etc...
if (something) {doIt();
}// This happens only 10% of the time, and then you
// better think twice about not doing it
else {dontDoIt();
}
在第二种情况下,我实际上是分别记录“ if”和“ else”情况。 我没有记录对“ dontDoIt()”的调用。 这可以进一步:
// This is the case when something happens and blah
// blah blah, and then, etc...
if (something) {doIt();
}// Just in case
else if (somethingElse) {doSomethingElse();
}// This happens only 10% of the time, and then you
// better think twice about not doing it
else {dontDoIt();
}
或使用try-catch-finally:
// Let's try doing some business
try {doIt();
}// IOExceptions don't really occur
catch (IOException ignore) {}// SQLExceptions need to be propagated
catch (SQLException e) {throw new RuntimeException(e);
}// Clean up some resources
finally {cleanup();
}
看起来很整洁,不是吗? 与此相反:
// Let's try doing some business
try {doIt();
} catch (IOException ignore) {// IOExceptions don't really occur
} catch (SQLException e) {// SQLExceptions need to be propagatedthrow new RuntimeException(e);
} finally {// Clean up some resourcescleanup();
}
我很好奇您的想法...
参考: if – else,来自JAVA,SQL和ANDJOOQ博客的JCG合作伙伴 Lukas Eder 编码风格最佳实践 。
翻译自: https://www.javacodegeeks.com/2012/01/if-else-coding-style-best-practices.html