Java 制作一个空字符串常量值得吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/213985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:29:12  来源:igfitidea点击:

Is making an empty string constant worth it?

javastring

提问by jacobko

I have a co-worker that swears by

我有一个同事发誓

//in a singleton "Constants" class
public static final String EMPTY_STRING = "";

in a constants class available throughout the project. That way, we can write something like

在整个项目中可用的常量类中。这样,我们可以写出类似的东西

if (Constants.EMPTY_STRING.equals(otherString)) {
    ...
}

instead of

代替

if ("".equals(otherString)) {
    ...
}

I say it's

我说是

  1. not worth it--it doesn't save any space in the heap/stack/string pool,
  2. ugly
  3. abuse of a constants class.
  1. 不值得——它不会在堆/堆栈/字符串池中节省任何空间,
  2. 丑陋的
  3. 滥用常量类。

Who is the idiot here?

谁是这里的白痴?

采纳答案by Dan Dyer

String literals are interned by default, so no matter how many times you refer to ""in code, there will only be one empty String object. I don't see any benefit in declaring EMPTY_STRING. Otherwise, you might as well declare ONE, TWO, THREE, FOUR, etc. for integer literals.

默认情况下,字符串字面值是 intern 的,所以无论你在代码中引用多少次"",都只会有一个空的 String 对象。我认为声明 EMPTY_STRING 没有任何好处。否则,您不妨为整数文字声明 ONE、TWO、THREE、FOUR 等。

Of course, if you want to change the value of EMPTY_STRING later, it's handy to have it in one place ;)

当然,如果你以后想改变 EMPTY_STRING 的值,把它放在一个地方很方便;)

回答by shelfoo

I much prefer seeing EMPTY_STRING.

我更喜欢看到 EMPTY_STRING。

It makes it english. "".equals 'reads' differently than EMPTY_STRING.equals.

它使它成为英语。"".equals '读取' 与 EMPTY_STRING.equals 不同。

回答by Bill K

  1. yes--it offers no benefit.
  2. depends on what you're used to, I'm sure.
  3. No, it's just a constant--not an abuse.
  1. 是的——它没有任何好处。
  2. 取决于你习惯了什么,我敢肯定。
  3. 不,这只是一个常数——而不是滥用。

回答by David G

I don't like either choice. Why not if (otherString.length() == 0)

两种选择我都不喜欢。为什么不if (otherString.length() == 0)

Edit: I actually always code

编辑:我实际上总是编码

if (otherString == null || otherString.length() == 0)

回答by Douglas Squirrel

Why on earth would you want a global variable in Java? James Gosling really tried to get rid of them; don't bring them back, please.

你到底为什么要在 Java 中使用全局变量?James Gosling 真的很想摆脱他们。请不要把他们带回来。

Either

任何一个

0 == possiblyEmptyString.length()

or

或者

possiblyEmptyString.isEmpty() // Java 6 only

are just as clear.

一样清楚。

回答by David Arno

Ironically the whole point of constants is to make them easily changeable. So unless your co-worker plans to redefine EMPTY_STRING to be something other than an empty string - which would be a really stupid thing to do - casting a genuine fixed construct such as "" to a constant is a bad thing.

具有讽刺意味的是,常量的全部意义在于使它们易于更改。因此,除非您的同事计划将 EMPTY_STRING 重新定义为空字符串以外的其他内容 - 这将是一件非常愚蠢的事情 - 将真正的固定构造(例如“”)转换为常量是一件坏事。

As Dan Dyer says, its like defining the constant ONE to be 1: it is completely pointless and would be utterly confusing - potentially risky - if someone redefined it.

正如 Dan Dyer 所说,这就像将常量 ONE 定义为 1 一样:它完全没有意义,并且如果有人重新定义它会完全令人困惑——可能有风险。

回答by Jon Skeet

The same argument comes up in .NET from time to time (where there's already a readonly static field string.Empty). It's a matter of taste - but personally I find "" less obtrusive.

.NET 中不时出现相同的论点(那里已经有一个只读静态字段 string.Empty)。这是一个品味问题 - 但我个人觉得“”不那么突兀。

回答by questzen

Hmm, the rules are right but are being taken in a different sense! Lets look at the cause, firstly all object references in java are checked by equals(). Earlier on, in some languages it was done using '==' operator, if by accident someone used '=' for '==', a catastrophe. Now the question of magic numbers/constants, for a computer all constants/numbers are similar. Instead of 'int ONE=1' one can surely use 1, but will that hold true for double PI = 3.141...? What happens if someone tries to change the precision sometime later.

嗯,规则是对的,但在不同的意义上被理解了!让我们看看原因,首先java中的所有对象引用都由equals()检查。早些时候,在某些语言中,它是使用“==”运算符完成的,如果有人不小心将“=”用于“==”,那将是一场灾难。现在是幻数/常数的问题,对于计算机来说,所有常数/数字都是相似的。肯定可以使用 1 而不是 'int ONE=1' ,但是这是否适用于 double PI = 3.141...?如果有人稍后尝试更改精度会发生什么。

If we were to come up with a check list, what would the rule be address the general guideline isn't it? All I mean to say is that rules are supposed to aid, we can surely bend the rules only when we know them very well. Common sense prevails. As suggested by a friend of mine, program constants like 0/1 which denote exit conditions can be hard coded and hence magic number principle doesn't apply. But for those which participate in logical checks/rules, better keep them as configurable constants.

如果我们想出一个检查清单,规则是什么?一般指导方针不是吗?我的意思是说,规则应该是有帮助的,只有当我们非常了解规则时,我们才能改变规则。常识占上风。正如我的一个朋友所建议的,像 0/1 这样表示退出条件的程序常量可以硬编码,因此幻数原理不适用。但是对于那些参与逻辑检查/规则的人,最好将它们保留为可配置的常量。

回答by John Nilsson

We just do the following for situations like this:

我们只是针对这样的情况执行以下操作:

public class StaticUtils
{
    public static boolean empty(CharSequence cs)
    {
        return cs == null || cs.length() == 0;
    }

    public static boolean has(CharSequence cs)
    {
        return !empty(cs);
    }
}

Then just import static StaticUtils.*

那么就 import static StaticUtils.*

回答by tvanfosson

I'm with your coworker. While the empty string is hard to mistype, you can accidentally put a space in there and it may be difficult to notice when scanning the code. More to the point it is a good practice to do this with all of your string constants that get used in more than one place -- although, I tend to do this at the class level rather than as global constants.

我和你的同事在一起。虽然空字符串很难打错,但您可能会不小心在其中放置一个空格,并且在扫描代码时可能很难注意到。更重要的是,对在多个地方使用的所有字符串常量执行此操作是一种很好的做法——尽管我倾向于在类级别而不是作为全局常量执行此操作。

FWIW, C# has a static property string.Empty for just this purpose and I find that it improves the readability of the code immensely.

FWIW,C# 有一个静态属性 string.Empty 就是为了这个目的,我发现它极大地提高了代码的可读性。