您对方法范围常量有何看法? [英] What are your thoughts on method scoped constants?

查看:100
本文介绍了您对方法范围常量有何看法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

public void doSomething() {

    final double MIN_INTEREST = 0.0;

    // ...  
}

我个人而言宁愿看到这些在类级别静态声明的替换常量。
我想我正在寻找关于这个问题的行业观点。

Personally, I would rather see these substitution constants declared statically at the class level. I suppose I'm looking for an "industry viewpoint" on the matter.

推荐答案

我的起始位置是应该声明/初始化每个变量或常量,尽可能接近它的第一次使用(即不要将代码的逻辑块分成两半,只是为了声明几行),并尽可能紧密地确定范围。 - 除非你能给我一个很好的理由,为什么它应该是不同的。

My starting position is that every variable or constant should be declared/initialized as close to it's first use as possible/practical (i.e. don't break a logical block of code in half, just to declare a few lines closer), and scoped as tightly as possible. -- Unless you can give me a damn good reason why it should be different.

例如,在公共API中不会显示方法作用域final。有时这些信息对你班级的用户来说可能会有用,并且应该向上移动。

For example, a method scoped final won't be visible in the public API. Sometimes this bit of information could be quit useful to the users of your class, and should be moved up.

在你提出的问题的例子中,我会说MIN_INTEREST可能是用户想要掌握的那些信息之一,它应该是范围的,而不是方法。 (虽然示例代码没有上下文,但我的假设可能完全错误。)

In the example you gave in the question, I would say that MIN_INTEREST is probably one of those pieces of information that a user would like to get their hands on, and it should be scoped to the class, not the method. (Although, there is no context to the example code, and my assumption could be completely wrong.)

这篇关于您对方法范围常量有何看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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