toString():用于调试还是用于人类?

发布于 2024-10-13 10:57:12 字数 402 浏览 5 评论 0原文

class Address
{
  private enum Component
  {
    NUMBER,
    STREET,
    STATE,
    COUNTRY
  }

  private Map<Component, String> componentToValue = ...;
}

我希望我的类包含两种方法:

  1. 一种用于指示每个地址组件的值(这样我可以在出现问题时进行调试)。
  2. 以人类期望的形式返回地址:“1600 Amphitheatre Parkway Mountain View, CA 94043”。

Object.toString() 的最佳实践是什么?它主要是针对#1还是#2?这些方法的命名是否有最佳实践?

class Address
{
  private enum Component
  {
    NUMBER,
    STREET,
    STATE,
    COUNTRY
  }

  private Map<Component, String> componentToValue = ...;
}

I'd like my class to contain two methods:

  1. One to indicate the value of each address component (so I can debug if anything goes wrong).
  2. One to return the address in a form expected by humans: "1600 Amphitheatre Parkway Mountain View, CA 94043".

What is the best-practice for Object.toString()? Is it primary meant for #1 or #2? Is there a best-practice for the naming of these methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(7

雪化雨蝶 2024-10-20 10:57:12

您是否会在 SMS 消息和 HTML 页面中以相同的方式设置地址格式?英语、法语和日语的格式是否相同?

如果不是,那么您就有了答案:表示不属于该对象,而是属于显示该对象的表示层。除非该对象是专门为表示层制作的,例如如果它是 HtmlI18nedAddress,则使用 toString 进行调试。

考虑 DateSimpleDateFormatDate 包含状态,SimpleDateFormat 返回多种表示形式。

Would you format an address the same way in a SMS message and in an HTML page? Would you format it the same way in English, French and Japanese?

If no, then you have your answer : the presentation does not belong to the object, but to the presentation layer displaying the object. Unless the object is specifically made up for the presentation layer, for example if it is a HtmlI18nedAddress, use toString for debugging.

Consider Date vs SimpleDateFormat. Date contains the state and SimpleDateFormat returns multiple representations.

挽心 2024-10-20 10:57:12

我想说的是第一个。数据格式化不应硬编码到对象的 ToString() 函数中。

我这样看:我尝试使 ToString() 输出数据可由匹配的 Parse(string data) 函数读取(该函数是否实际存在并不重要)。因此,在这种情况下,如果您想要特定的格式,请编写特定的函数,并将通用数据转储例程留给 ToString()。

I would say the first. Data formatting should not be hard coded into the ToString() function of the object.

I look at it this way: I try to make my ToString() output data that is readable by a matching Parse(string data) function (if that function actually exists or not is not important). So in this case, if you want a specific formatting, write a specific function, and leave the generic data dump routines to ToString().

時窥 2024-10-20 10:57:12

我通常使用 Apache Commons ToStringBuilder http: //commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/ToStringBuilder.html 仅包含我认为调试绝对必要的部分。

I normally use the Apache Commons ToStringBuilder http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/ToStringBuilder.html with only the parts that I think are absolutely necessary for debugging.

陌伤ぢ 2024-10-20 10:57:12

根据 Effective Java 第 12 项:“始终重写 toString “toString() 的约定是:

结果应该是简洁但信息丰富的表示形式,易于人们阅读。 [...]提供良好的 toString 实现可以使您的类更易于使用,并使使用该类的系统更易于调试

因此,它是为了调试。

关于toString()的更多注释:

  • 添加JavaDoc(这里应该解释格式)
  • 一旦格式固定,请记住该格式将用于解析。

我强烈推荐投资《Effective Java》这本书。这是一本非常好的读物。一个项目只需五到十分钟,但您的 Java 生活将永远改变!

According to Effective Java Item 12: "Always override toString" the contract for toString() is:

The result should be a concise but informative representation that is easy for a person to read. [...] providing a good toString implementation makes your class much more pleasant to use and makes systems using the class easier to debug.

Thus, it is for debugging.

More notes on toString():

  • Add JavaDoc (the format should be explained here)
  • As soon as the format is fixed, keep in mind that the format will be used for parsing.

I highly recommend investing in the book "Effective Java". It is a very nice read. Just five to ten minutes for an item, but your Java live will change forever!

神仙妹妹 2024-10-20 10:57:12

您可以从动态配置的某些调试属性中读取:

@Override
public String toString() { 

    if(debug) {
        return debugAddrString()
    }
    return normalAddrString();

}

You could read from some debug property that you configure dynamically.:

@Override
public String toString() { 

    if(debug) {
        return debugAddrString()
    }
    return normalAddrString();

}
野侃 2024-10-20 10:57:12

ToString 通常应该仅用于调试信息。请记住,您正在重写 Object 上的方法;对 Object 引用进行方法调用返回人类可读的地址在概念上准确吗?在某些情况下,根据项目的不同,这实际上可能是有意义的,但对我来说听起来有点奇怪。我会实施一种新方法。

另一件需要注意的事情是,大多数现代 IDE 在检查对象时使用 ToString 方法来打印有关对象的调试信息。

ToString should generally only be used for debug information. Keep in mind that you're overriding a method on Object; is it conceptually accurate to have a method call on an Object reference return a human readable address? In some cases, depending on the project, this may actually make sense, but it sounds a bit odd to me. I would implement a new method.

Another thing to note is that most modern IDEs use the ToString method to print debug information about objects when inspecting them.

空城之時有危險 2024-10-20 10:57:12

您可以做的一件事是使用调试标志来根据需要更改此设置:

public String toString(boolean debug) {
    if (debug) return debugStringVersion;
    else return humanVersion;
}

public String toString() {
    return toString(Util.DEBUG);
}

当然,这假设您有一个带有调试标志的实用程序类。

One thing you can do is use a Debug flag to change this as you like:

public String toString(boolean debug) {
    if (debug) return debugStringVersion;
    else return humanVersion;
}

public String toString() {
    return toString(Util.DEBUG);
}

Of course this assumes that you have a utility class suet up with a debug flag in it.

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