【问题标题】:How would you write this piece of code with lots of if-statements better? [closed]您如何更好地编写带有大量 if 语句的这段代码? [关闭]
【发布时间】:2018-06-19 22:30:15
【问题描述】:
    if (right == null && parent == null)
        return null;
    else if (right == null)
        return parent;
    else if (parent == null)
        return right;
    else
        return parent.val > right.val ? right : parent;

    if (right == null && parent == null)
        return null;
    else if (right == null || parent == null)
        return parent == null ? right : parent;
    else
        return parent.val > right.val ? right : parent;

或者你有什么其他建议吗?我正在寻找一个干净的代码。

【问题讨论】:

  • 如果这是你想要改进的工作代码,它应该在Code Review
  • 任何时候你的代码遇到return,你就不需要else
  • @Turing85 你的建议更糟。
  • 我投票结束这个问题,因为它应该在代码审查中。
  • @PraveenKumar 这可能会作为代码审查的示例代码存根被关闭。

标签: java code-readability


【解决方案1】:

您不需要检查两者是否为空。下面的第一个 if 语句将为您执行此操作(因为如果 rightparent 为 null,则将返回 null)。

if (right == null) {
    return parent;
}

if (parent == null) {
    return right;
}

return parent.val > right.val ? right : parent;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2013-03-11
    相关资源
    最近更新 更多