使用带有fallthrough的开关来处理Javascript中的默认参数是个好主意吗?

发布于 2024-12-25 04:51:38 字数 1893 浏览 3 评论 0 原文

我最近了解到,您可以使用带有 Fallthrough 的简洁 switch 语句来设置 Javascript 中的默认参数值:

function myFunc(arg1, arg2, arg3) {
    //replace unpassed arguments with their defaults:
    switch (arguments.length) {
        case 0 : arg1 = "default1";
        case 1 : arg2 = "default2";
        case 2 : arg3 = "default3";
    }
}

我越来越喜欢它,因为它不仅非常短,而且还基于实际传递的参数来工作,而不依赖于它在使用特殊类别的值(null、falsy 等)作为占位符时,就像在更传统的版本中一样

function myFunc(arg1, arg2, arg3){
    //replace falsy arguments with their defaults:
    arg1 = arg1 || "default1";
    arg2 = arg2 || "default2";
    arg3 = arg3 || "default3";
}

: <代码>||

开关fallthough 不会让它变得更长,而且它的优点是它更加“健壮”,因为它不关心参数的类型。在一般情况下,每当我必须使用默认参数创建一个函数时,不必担心所有虚假值(''、0、null、false ...)会发生什么,这听起来是个好主意。

然后我会保留 arg = arg || x 用于我想检查真实性的实际情况,而不是将其重新用作参数默认的一般规则。

但是,我发现 这种模式的示例很少 .length%5Cs%2a%5C%29%20lang%3a%5Ejavascript%24&type=cs" rel="nofollow">代码搜索,所以我不得不穿上我的怀疑论者的帽子。 为什么我没有找到更多这个习语的例子?

  • 它现在才广为人知吗?
  • 是我搜索得不够仔细吗?我是否对大量误报感到困惑?
  • 有什么东西让它不如其他替代品吗?

我(以及一些评论)可以想到避免 switch(arguments.length) 的一些原因:

  • 使用通过对象文字传递的命名参数非常灵活且可扩展。也许更多可选参数的地方正在使用它?

  • 也许大多数时候我们确实想要检查真实性?使用一类值作为占位符还允许默认参数出现在中间而不是仅出现在末尾: myFunc('arg1', null, 'arg3')

  • 也许大多数人更喜欢非常短的 arg = arg || “default” 并且大多数时候我们并不关心虚假值?

  • 也许访问arguements是邪恶的/表现不佳?

  • 也许这种开关盒失效有一个我没有想到的不好的部分?

这些缺点是否足以避免使用 switch(arguments.length) 作为主要的默认参数模式,或者这是我应该在代码中保留和使用的巧妙技巧?

I have recently learned that you can use a neat switch statement with fallthrough to set default argument values in Javascript:

function myFunc(arg1, arg2, arg3) {
    //replace unpassed arguments with their defaults:
    switch (arguments.length) {
        case 0 : arg1 = "default1";
        case 1 : arg2 = "default2";
        case 2 : arg3 = "default3";
    }
}

I have grown to like it a lot, since not only is it very short but it also works based on parameters actually passed, without relying on having a special class of values (null, falsy, etc) serve as placeholders as in the more traditional versions:

function myFunc(arg1, arg2, arg3){
    //replace falsy arguments with their defaults:
    arg1 = arg1 || "default1";
    arg2 = arg2 || "default2";
    arg3 = arg3 || "default3";
}

My inital though after seeing the version using the switch was that I should consider using it "by default" over the || version.

The switch fallthough makes it not much longer and it has the advantage that it is much more "robust" in that it does not care about the types of the parameters. In the general case, it sounds like a good idea to not have to worry about what would happen with all the falsy values ('', 0, null, false ...) whenever I have to make a function with default parameters.

I would then reserve the arg = arg || x for the actual cases where I want to check for truthyness instead of repurposing it as the general rule for parameter defaulting.

However, I found very few examples of this pattern when I did a code search for it so I had to put on my skeptic hat. Why didn't I find more examples of this idiom?

  • Is it just now very well known?
  • Did I not search well enough? Did I get confused by the large number of false positives?
  • Is there something that makes it inferior to the alternatives?

Some reasons that I (and some of the comments) could think of for avoiding switch(arguments.length):

  • Using named parameters passed via an object literal is very flexible and extensible. Perhaps places where more arguments can be optional are using this instead?

  • Perhaps most of the time we do want to check for truthyness? Using a category of values as palceholders also allows default parameters to appear in the middle instead of only at the end : myFunc('arg1', null, 'arg3')

  • Perhaps most people just prefer the very short arg = arg || "default" and most of the time we just don't care about falsy values?

  • Perhaps accessing arguements is evil/unperformant?

  • Perhaps this kind of switch case fallthrough has a bad part I didn't think about?

Are these cons enough to avoid using switch(arguments.length) as a staple default argument pattern or is it a neat trick I should keep and use in my code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沒落の蓅哖 2025-01-01 04:51:38

既然问题已经更新了,这确实是一个见仁见智的问题。许多人建议避免使用许多 JavaScript 功能,例如 switch 和三元。这就是为什么关于其中一些功能的信息不多的原因。

提出这个建议的原因是因为许多人错误地使用了这些功能并在他们的代码中产生了问题。这些错误有时很难检测到,其他人也很难理解您的代码在做什么(特别是那些不熟悉 javascript 的人或新程序员)。

因此,如果您喜欢这样做,并且您不担心编写您的代码的任何人的意见(或技能水平)。无论如何,你的方法将会奏效。我自己有时也使用过 switch 语句,虽然我不认为它真的“好”或“坏”,但很难找到需要它的情况。

你问我如何在没有 if-else 链的情况下解决这个问题:

function myFunc(args) {
    var allArgs = {
        arg1:"default1",
        arg2:"default2",
        arg3:"default3"
    };
    for (var key in args) {
        allArgs[key] = args[key];        
    }
}
myFunc({arg1:null, arg3:'test'})

Since the question has been updated, it's really a matter of opinion. There are a number of javascript features that many people suggest avoiding, such as switch and ternary. This is why there is not a lot of information on some of those features.

The reason that suggestion is made is because many people miss-use those features and create problems in their code. The bugs are sometimes difficult to detect and it can be difficult for others to understand what your code is doing (particularly those unfamiliar with javascript or new programmers).

So if you like to do it that way, and you're not worried about the opinions (or skill level) of anyone working on your code. By all means, your approach will work. I have used the switch statement myself on occasion, and while I don't think it's really "good" or "bad", it's hard to find a situation that requires it.

You asked how I might go about this without an if-else chain:

function myFunc(args) {
    var allArgs = {
        arg1:"default1",
        arg2:"default2",
        arg3:"default3"
    };
    for (var key in args) {
        allArgs[key] = args[key];        
    }
}
myFunc({arg1:null, arg3:'test'})
烦人精 2025-01-01 04:51:38

只是猜测,但 Doug Crockford 不鼓励在“JavaScript:优秀部分”中使用 switch 语句。他的逻辑是 switch 语句是错误的常见来源,因为在使用“失败”逻辑时很难找到它们。很容易看出某个案例何时被触发,但通常很难确定结果集中的每个案例是否都已被覆盖,特别是如果它不是您的代码。

Just a guess, but Doug Crockford discourages the use of switch statements in 'JavaScript: the Good Parts.' His logic is that switch statements are a common source of bugs because it's difficult to locate them when using 'fall through' logic. It's easy to see when a case is triggered, but it's often difficult to determine if every case in a result set has been covered, especially if it's not your code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文