与函数参数具有相同含义的局部变量的约定是什么?
与函数参数具有相同含义的局部变量的约定是什么?
如果我需要将函数参数作为其初始状态值的局部变量(因此具有相同含义),我应该如何称呼它?
作为一个人工示例(然而,这演示了 Clojure 中相当流行的构造):
(defn sum [coll]
(loop [local-coll coll, result 0]
(if (empty? local-coll)
result
(recur (rest local-coll) (+ (first local-coll) result)))))
这里 local-coll
最初被初始化为 coll
的值,并且在循环播放。 local-coll
绝对不是一个好名字,但是什么是呢?
在 Haskell 中,将引号 ('
) 放在变量/函数名称的末尾是一种很好的风格,例如 var'
。在 Common Lisp 中,有时我会看到名称以星号 (*
) 结尾。 Clojure 对函数有相同的表示法,它重复了另一个函数的含义,但语义略有不同(例如列表*)。但这种表示法也经常在文档字符串中使用,以指示可能存在多个这种类型的项目(例如 (methodname [args*] body)*
或 (try expr* catch-clause* finally-clause?)
),因此在用于本地变量名称时可能会造成混淆。 Java 互操作还提供诸如 defn-
之类的功能,即以连字符 (-
) 结尾的名称,以指示生成的类中的私有方法。因此,对本地(函数私有)变量使用连字符也是有意义的(尽管对我来说似乎有点奇怪)。
那么,当我的局部变量的命名与函数参数的含义相同时,我应该怎么做呢?
What is convention for local vars that has same meaning as function argument?
If I need local variable that has as its initial state value of function argument (and thus has the same meaning), how should I call it?
As artificial example (that, however, demonstrates quite popular construction in Clojure):
(defn sum [coll]
(loop [local-coll coll, result 0]
(if (empty? local-coll)
result
(recur (rest local-coll) (+ (first local-coll) result)))))
Here local-coll
is initialized to the value of coll
initially, and it also holds this meaning during looping. local-coll
is definitely not a good name for it, but what is?
In Haskell it is a good style to put quote ('
) to the end of variable/function name, e.g. var'
. In Common Lisp sometimes I saw names ending with asterisk (*
). Clojure has same notation for function that duplicate another function meaning but have a bit different semantics (e.g. list*). But this notation is also frequently used in docstrings to indicate that there may be several items of this type (e.g. (methodname [args*] body)*
or (try expr* catch-clause* finally-clause?)
) and thus can confuse when used for local var names.
Java interop also provides things like defn-
, that is names ending with hyphen (-
) to indicate private methods in generated classes. So it makes some sense to use hyphen for local (private for a function) variables too (though it seems a bit weird for me).
So, what the way should I go when naming my local variables with the same meaning as function argument?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为当您不再需要原始参数时,隐藏参数名称是很好的:
我见过的其他变体是:
I think it's fine to shadow the argument name when you don't need the original argument any more:
Other variations that I've seen are: