函数级常量 - 在函数顶部声明?
我有一个常量值,我只计划在我的代码库中使用一次。 我将使用 const
声明来声明它。
如果这是一个函数级变量,我会在使用时声明它,但使用常量这样做似乎会使我的函数变得混乱。
I have a constant value that I only plan to use once in my codebase. I am going to declare it using a const
declaration.
If this was a function-level variable I would declare it at the point of usage, but doing so with a constant just seems to clutter my function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用常量而不是硬编码值的两个原因是为了可读性,因此以后可以轻松找到和更改它,对吧? 因此,将其声明在以后最容易找到的地方。 通常我发现它位于函数、类或文件的开头——同样,无论范围如何有意义。
The two reasons for using a constant instead of hard-coding a value is for readability and so it can be easily found and changed later, right? So declare it where it would be most easily found later. Usually I find this is at the beginning of the function, class, or file - again, whatever scope makes sense.
我将常量视为一种配置。
如果它们可以改变,它们就会成为应用程序属性,
如果他们不能,我就把他们放在班上名列前茅
其中它们甚至可以用于函数级常量。
这样,您只需打开文件即可在一个列表中查看所有文件
I look a constants as a kind of configuration.
If they can change they become application properties,
if they can't I put them at the top of the class
in which they will be used even for function level constants.
This way you can just open the file and see them all in one list
我通常将它们声明为尽可能靠近我将使用它们的地方。
原因是,当我浏览其他人的代码时,必须在文件中跳来跳去才能了解发生了什么,非常不方便。 因此,我自己编写代码时会尽量让其他人变得容易。
对于函数顶部的小函数可以增加可读性(从而提高其他人的可理解性),因此这条规则远非一成不变。
I usually declare them as close to where I'll use them as possible.
Reason is that when I'm going through other people's code, it's very inconvenient to have to jump up and down a file to understand what's going on. So I try to make it easy on others when writing code myself.
For small(ish) function at the top of the function could increase readability (and hence understandability for others), so this rule is far from etched in stone.
我将它们放在文件的开头,将它们视为整个类的配置。 此外,在编码时,只需将鼠标悬停在任何位置,您闪亮的 IDE 就会告诉您它的价值。
如果它还没有引入您的常量,对其进行编码,然后在完成重构后尝试您想要的任何内容,并将其设为常量,那么您就不会不断更改它。
I put them in the beginning of the file, treats them as configuration all over the class. Also while coding just mouse-over and regardless of the location your shiny IDE will tell you the value of it.
It's not something you keep changing if it's don't introduce your constant yet, code it, try whatever you want then when you done refactor, and make it a constant.