可以添加 toString() 来简化调试吗?

Is it ok to add toString() to ease debugging?

我在 intellij 中工作很多,让 类 拥有自己的 tostring(在 intellij 中生成的可以很好地工作)会很方便,这样你在尝试时可以看到比 MyClass@1345 更有信息的东西弄清楚是什么东西。

我的问题是:可以吗?我正在添加没有商业价值并且不会影响我的测试用例或我的软件执行的代码(我没有使用 toString() 除了调试之外的任何东西)。尽管如此,它仍然是我过程的一部分。什么是正确的?

toString()方法主要设计为调试目的方法。
除了一些特殊情况,您应该赞成将其用于调试目的,而不是向客户端显示信息,因为客户端的需求今天可能与 toString() 方法不同或相同,但明天可能会有所不同。

toString() javadoc,您可以阅读:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

对您来说重要的部分是:

The result should be a concise but informative representation that is easy for a person to read.

It is recommended that all subclasses override this method.

你是这么说的:

Still, it is a part of my process. What is correct here?

好东西:规范推荐。

完全没问题,甚至是个好主意。大多数 classes 不指定 toString 的内容,因此将其用于逻辑是不明智的(内容可能会在 class 的未来版本中更改)。但是有些 classes 会,例如 StringBuilder。然后逻辑用return值也是可以的。

因此,对于您自己的 classes,您甚至可以选择指定内容并使用(并让您的用户使用)return 逻辑值。

除了 davidxxx 的优秀观点外,以下内容也适用:

  • 一致性 很重要。使用您的代码的人 不会 对您 类 中发生的事情感到惊讶。所以要么 "all/most" 类 @override toString() 使用类似的实现 - 或者 "none" 这样做。
  • 因此:确保每个人都同意 if/how 实施 toString()
  • 特别确保您的 toString() 实施 稳健

意思是:您绝对必须避免您的实现抛出任何异常(例如 NPE,因为您碰巧对某些可能为空的 fieldX 执行了 someString + fieldX.name())。

您还必须避免创建 "expensive" 实现(例如,对某些数据库执行 "deep dive" 以从那里获得值的 return 的代码)。

2 cent of personal opinion: 我发现 toString() 在调试东西时有很大的价值;但我也看到 toString() 过于昂贵 对性能的实际影响。问题是:您不知道某些跟踪代码对您的对象调用 toString() 的频率;所以你最好确保returns .

docs解释一下这个方法的功能:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

如您所见,他们没有指定此方法的特定用途或不鼓励您使用它进行调试,但他们只说明了预期的用途,并且还建议在 Object 的子类中实现此方法。

因此严格来说,如何使用此方法取决于您。在我上的大学课程中,某些任务需要覆盖 toString 方法,并且在某些情况下我们被要求使用它来演示调试。