Item 12: Always override toString

笔记

  • The general contract for toString says that the returned string 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方法。. It consists of the class name followed by an “at” sign (@) and the unsigned hexadecimal representation of the hash code, for example, PhoneNumber@163b91.

  • While it isn’t as critical as obeying the equals and hashCode contracts (Items 10 and 11), providing a good toString implementation makes your class much more pleasant to use and makes systems using the class easier to debug.
    不强制要求,属于锦上添花的事情。

  • When practical, the toString method should return all of the interesting information contained in the object。
    方便调试和记录日志。如果只包含部分字段,在这些字段内容相同的时候,容易造成混淆,不能区分具体的对象。

  • to specify the format of the return value in the documentation. It is recommended that you do this for value classes。 If you specify the format, it’s usually a good idea to provide a matching static factory or constructor so programmers can easily translate back and forth between the object and its string representation.
    对于值类,可以声明toString返回值的格式。如果要解析返回值,最好是由类的发布者提供工具方法。后面有变动,可以同步修改实现。不至于造成用户不能感知到的变更。

  • Whether or not you specify the format, provide programmatic access to the information contained in the value returned by toString.
    一定要为toString中包含的信息提供访问方法,不要去解析toString返回的内容。这个内容不稳定,不可信赖,容易引入bug。

  • You should, however, write a toString method in any abstract class whose sub·classes share a common string representation.
    可以在抽象类中实现toString方法,条件是子类共享相同的表示形式。

  • Google’s open source AutoValue facility, discussed in Item 10, will generate a toString method for you, as will most IDEs.
    偷懒工具。

  • To recap, override Object’s toString implementation in every instantiable class you write, unless a superclass has already done so.

理解与思考

  1. 覆写toString方法,返回可读性高的内容,主要是为了方便调试和记录日志。
  2. 不要试图去解析toString方法的返回值。如果要解析,也最好由类提供方给出解析方法,方便扩展。
  3. toString的输出内容要覆盖equals方法里用到的字段,否则容易丢掉信息,不利于定位。

实践

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,223评论 0 13
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,965评论 0 0
  • 我可以说是一个“拜金女”。我可以毫不避讳的告诉你我喜欢钱,当我还是一个高中刚毕业的小不点时,我没有任何的经济来源...
    CC灿宝阅读 1,414评论 0 1
  • 钥匙去哪里了 周五的早上,学校一老师向我借图书室的钥匙,想去给孩子选几本书,当我拉开放钥匙的小格子的时候,心里一咯...
    河南郑州毛秋风阅读 1,378评论 0 0
  • 多少次想试着逃离的城市 离开时竟有点想念 我即将从一个车水马龙的地方 回归原始的乡村生活 山间的鸟鸣代替了街头的鸣...
    钟春生的诗阅读 1,346评论 0 2

友情链接更多精彩内容