编程风格:如果不满足警卫条件,您应该早点回来吗? [英] Programming style: should you return early if a guard condition is not satisfied?

查看:85
本文介绍了编程风格:如果不满足警卫条件,您应该早点回来吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时想知道的一件事是下面显示的两种样式中最好的一种(如果有的话)?如果没有满足保护条件,最好立即返回,还是仅当满足保护条件 时,您才做其他事情?

One thing I've sometimes wondered is which is the better style out of the two shown below (if any)? Is it better to return immediately if a guard condition hasn't been satisfied, or should you only do the other stuff if the guard condition is satisfied?

为了论证,请假设保护条件是返回布尔值的简单测试,例如检查某个元素是否在集合中,而不是通过引发异常来影响控制流的东西.还要假设方法/功能足够简短,不需要滚动编辑器.

For the sake of argument, please assume that the guard condition is a simple test that returns a boolean, such as checking to see if an element is in a collection, rather than something that might affect the control flow by throwing an exception. Also assume that methods/functions are short enough not to require editor scrolling.

// Style 1
public SomeType aMethod() {
  SomeType result = null;

  if (!guardCondition()) {
    return result;
  }

  doStuffToResult(result);
  doMoreStuffToResult(result);

  return result;
}

// Style 2
public SomeType aMethod() {
  SomeType result = null;

  if (guardCondition()) {
    doStuffToResult(result);
    doMoreStuffToResult(result);
  }

  return result;
}

推荐答案

我更喜欢第一种样式,除了在不需要它时不会创建变量.我会这样做:

I prefer the first style, except that I wouldn't create a variable when there is no need for it. I'd do this:

// Style 3
public SomeType aMethod() {

  if (!guardCondition()) {
    return null;
  }

  SomeType result = new SomeType();
  doStuffToResult(result);
  doMoreStuffToResult(result);

  return result;
}

这篇关于编程风格:如果不满足警卫条件,您应该早点回来吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆