下面的帖子將是一個高級花括號討論,沒有對與錯的答案,只是更多的“品味”。 它是關于是否將“ 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