如果–否则为编码风格最佳实践
生活随笔
收集整理的這篇文章主要介紹了
如果–否则为编码风格最佳实践
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
下面的帖子將是一個(gè)高級(jí)花括號(hào)討論,沒有對(duì)與錯(cuò)的答案,只是更多的“品味”。 它是關(guān)于是否將“ else”(以及其他關(guān)鍵字,例如“ catch”,“ finally”)放在換行符上。
有些人可能會(huì)寫
if (something) {doIt(); } else {dontDoIt(); }但是,我更喜歡
if (something) {doIt(); } else {dontDoIt(); }這看起來(lái)很愚蠢。 但是評(píng)論呢? 他們?nèi)ツ睦?#xff1f; 這在我看來(lái)有點(diǎn)不對(duì)勁:
// 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(); }在第二種情況下,我實(shí)際上是分別記錄“ if”和“ else”情況。 我沒有記錄對(duì)“ dontDoIt()”的調(diào)用。 這可以進(jìn)一步:
// 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(); }看起來(lái)很整潔,不是嗎? 與此相反:
// 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,來(lái)自JAVA,SQL和ANDJOOQ博客的JCG合作伙伴 Lukas Eder 編碼風(fēng)格最佳實(shí)踐 。
翻譯自: https://www.javacodegeeks.com/2012/01/if-else-coding-style-best-practices.html
總結(jié)
以上是生活随笔為你收集整理的如果–否则为编码风格最佳实践的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 从MongoDB GridFS流式传输文
- 下一篇: 有道翻译在线使用免费