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

后端 未结 24 1966
心在旅途
心在旅途 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:14

    +1 Mike C

    Over and above its usefulness for debugging, the toString() is an invaluable tool to understand the class author's perspective of the instance.

    FWIW, if the output of the toString differs from what you expect to see (courtesy spec docs) you will know rightaway something went seriously wrong.

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

    If there is a problem with the existing toString() implementations, the developer should fix the problem. Saying the current implementations are all "pure cruft" and removing them is actively doing harm, unless the existing toString() methods are uncommonly poorly written.

    I would strongly discourage the developer from removing any functioning toString() method.

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

    Removing well-written (or even halfway decently written) toString() methods is pure insanity, IMO. Yes, I am often too lazy to write these (as often the objects don't end up having them used anyway), but they are extremely handy to have.

    I really can't think of a good reason to want to get rid of these.

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

    I always auto-generate toString() methods for all my POJOs, DTOs and/or any object that holds persistent data. For private internal properties good logging practice should do the trick.

    Always remember to replace in toString methods passwords and other sesitive info with [Omitted] (or something similar of top secrete nature)

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

    Personally, I implement them when I'm going to use objects in a JList, JTable, or other structure that uses toString() OR when I'm debugging (yes, eclipse has debug formatters but toString() is easier).

    Perhaps you can fire back that many JDK classes have toString(). Should they be removed as well? ;)

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

    For debugging purposes, no one can beat toString. It's practical both in a debugger, and in simple debug prints. Make sure it displays all the fields that your equals and hashCode methods are based on, if you override those as well!

    For display to end users, I wouldn't use toString, though. For that, I think it's better to write another method, that does the proper formatting, and i18n if you need that.

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