是否最好将代码封装到“IF”语句中,或者最好是“短路”函数并返回? [英] Is it better to wrap code into an 'IF' statement, or is it better to 'short circuit' the function and return?

查看:209
本文介绍了是否最好将代码封装到“IF”语句中,或者最好是“短路”函数并返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中做一些编码,我有很多实例,我必须检查一些东西,然后我继续。我陷入了在函数早期返回的习惯,但我不知道我是否这样做。我不知道它是否会对代码的复杂性产生影响。

I'm doing some coding in JavaScript, and I am having a lot of instances where I have to check some stuff before I proceed. I got into the habit of returning early in the function, but I'm not sure if I am doing this right. I am not sure if it have an impact on the complexity of my code as it grows.

我想知道更多经验丰富的JavaScript代码,什么是更好的通用实践以下两个例子。

I want to know from more experienced JavaScript coders, what is a better general practice out of the following two examples. Or is it irrelevant, and they are both OK ways of writing this particular IF block?

1)回到早期或短路我称之为(守卫条款),或者是不相关的,它们都是OK的方式写这个特定的IF块?

1) Returning Early or "Short Circuit" as I call it (Guard Clause).

ServeAlcohol = function(age)
{
     if(age < 19)
         return;


     //...Code here for serving alcohol.....
}

..或...

2)将代码包装到IF语句中。

2) Wrap code into an IF statement.

ServeAlcohol = function(age)
{
     if(age >= 19)
     {
          //...Code here for serving alcohol.....
     }
}


推荐答案

通常我有输入验证返回。想象一下,如果你有一堆条件,你会立即得到一个嵌套的如果。

Usually I have input-validation return right away. Imagine if you had a bunch of conditionals, you'd get a mess of nested ifs right away.

一般来说,一旦我得到过去的输入验证,我避免多个回报,但对于验证我马上回来。保持清洁IMHO。

Generally once I get past input validation I avoid multiple returns, but for validation I return right away. Keeps it cleaner IMHO.

这篇关于是否最好将代码封装到“IF”语句中,或者最好是“短路”函数并返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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