When is it desired to not implement toString() in Java?

后端 未结 24 1968
心在旅途
心在旅途 2020-12-10 00:45

A lead developer on my project has taken to referring to the project\'s toString() implementations as \"pure cruft\" and is looking to remove them from the code base.

<
相关标签:
24条回答
  • 2020-12-10 01:06

    We're getting a ConcurrentModificationException thrown out of one of our toString() methods, so there's an occasional drawback. Of course it's our own fault for not making it synchronized.

    0 讨论(0)
  • 2020-12-10 01:07

    It makes good sense because you always have problems with toStrings showing too little or too much information.

    It may make sense to your team to use the ToStringBuilder in Jakarta Commons Lang instead:

    System.out.println("An object: " + ToStringBuilder.reflectionToString(anObject));
    

    which introspects the object, and prints out the public fields.

    http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/builder/ToStringBuilder.html

    0 讨论(0)
  • 2020-12-10 01:10

    I would argue the opposite that toString() should be overriden judiciously. The default toString() implementation is very uninformative and basically useless. A good toString() implementation can give a developer a very useful view of the contents of the object at a glance. You may not have to put everything in there but at least the important stuff. I think your lead developer should be actually coding and adding features rather than worrying about "cruft".

    0 讨论(0)
  • 2020-12-10 01:11

    Although toString() methods are very useful for debugging value classes, it can be argued they are not useful for entity classes.

    0 讨论(0)
  • 2020-12-10 01:12

    I would only implement it for more complex objects where client code doesn't care about the fine grained details of the object state, but rather care about some more human understandable, sense making message, that summarizes what is going on, state wise...

    For everything else, like JavaBeans, I would expect client code to throw my object into a ToStringBuilder method or similar, if it needs to do low-level debugging.

    ToStringBuilder.reflectionToString(myObject);
    

    Or client code should just call standard property getters and log the way they like...

    0 讨论(0)
  • 2020-12-10 01:12

    I've said that doing so would mean that any clients wishing to display the objects would have to write their own code to convert the object to string, but that was answered with "yes they would".

    This is not a question that can be answered in isolation ... you should ask the clients (or the people writing them) what they think of the idea. If I was using a Java library and relying on its toString() overloads for debugging, I'd be rather annoyed if the library's developers decided to purge them.

    0 讨论(0)
提交回复
热议问题