最佳编码hdu_如果–否则为编码风格最佳实践

最佳编码hdu

以下文章将是一个高级大括号讨论,没有对与错的答案,只是更多的“品味”。 它是关于是否将“ 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 it
  dontDoIt();
}

以下不是更好吗?

// 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 propagated
  throw new RuntimeException(e);
} finally {
  // Clean up some resources
  cleanup();
}

我很好奇您的想法...

参考: if – else –来自JAVA,SQL和ANDJOOQ博客的JCG合作伙伴 Lukas Eder的编码风格最佳实践


翻译自: https://www.javacodegeeks.com/2012/01/if-else-coding-style-best-practices.html

最佳编码hdu

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值