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

后端 未结 24 1964
心在旅途
心在旅途 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 00:57

    I think the answer depends on how complicated your toString() methods are, how much work they require to maintain, and how often they get used. Assuming you use toString() often for logging and debugging it doesn't make much sense to remove these methods. But if they are rarely used and require a lot of work to maintain each time something changes in your code, then there is perhaps a valid argument for getting rid of all or some of the toString() methods.

    You mentioned something about clients needing to display these objects. From this I'm guessing your code is or contains some kind of library or API that other developers will use. In this case I highly recommend you maintain useful toString() implementations. Even if you don't do a lot of logging and debugging, your clients might and they will definitely appreciate having useful toString() methods that they don't have to write and maintain themselves.

提交回复
热议问题