函数级常量 - 在函数顶部声明?

发布于 2024-07-11 12:51:38 字数 119 浏览 6 评论 0原文

我有一个常量值,我只计划在我的代码库中使用一次。 我将使用 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 技术交流群。

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

发布评论

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

评论(4

末が日狂欢 2024-07-18 12:51:38

使用常量而不是硬编码值的两个原因是为了可读性,因此以后可以轻松找到和更改它,对吧? 因此,将其声明在以后最容易找到的地方。 通常我发现它位于函数、类或文件的开头——同样,无论范围如何有意义。

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.

稀香 2024-07-18 12:51:38

我将常量视为一种配置。
如果它们可以改变,它们就会成为应用程序属性,
如果他们不能,我就把他们放在班上名列前茅
其中它们甚至可以用于函数级常量。

这样,您只需打开文件即可在一个列表中查看所有文件

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

蝶舞 2024-07-18 12:51:38

我通常将它们声明为尽可能靠近我将使用它们的地方。

原因是,当我浏览其他人的代码时,必须在文件中跳来跳去才能了解发生了什么,非常不方便。 因此,我自己编写代码时会尽量让其他人变得容易。

对于函数顶部的小函数可以增加可读性(从而提高其他人的可理解性),因此这条规则远非一成不变。

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.

永不分离 2024-07-18 12:51:38

我将它们放在文件的开头,将它们视为整个类的配置。 此外,在编码时,只需将鼠标悬停在任何位置,您闪亮的 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.

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