编程风格:如果不满足警卫条件,您应该早点回来吗?

编程入门 行业动态 更新时间:2024-10-11 15:19:58
本文介绍了编程风格:如果不满足警卫条件,您应该早点回来吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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; }

更多推荐

编程风格:如果不满足警卫条件,您应该早点回来吗?

本文发布于:2023-10-28 01:24:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警卫   不满足   早点   风格   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!