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。
    方便調(diào)試和記錄日志。如果只包含部分字段,在這些字段內(nèi)容相同的時候,容易造成混淆,不能區(qū)分具體的對象。

  • 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返回值的格式。如果要解析返回值,最好是由類的發(fā)布者提供工具方法。后面有變動,可以同步修改實現(xiàn)。不至于造成用戶不能感知到的變更。

  • Whether or not you specify the format, provide programmatic access to the information contained in the value returned by toString.
    一定要為toString中包含的信息提供訪問方法,不要去解析toString返回的內(nèi)容。這個內(nèi)容不穩(wěn)定,不可信賴,容易引入bug。

  • You should, however, write a toString method in any abstract class whose sub·classes share a common string representation.
    可以在抽象類中實現(xiàn)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方法,返回可讀性高的內(nèi)容,主要是為了方便調(diào)試和記錄日志。
  2. 不要試圖去解析toString方法的返回值。如果要解析,也最好由類提供方給出解析方法,方便擴展。
  3. toString的輸出內(nèi)容要覆蓋equals方法里用到的字段,否則容易丟掉信息,不利于定位。

實踐

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,942評論 0 13
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 3,001評論 0 0
  • 我可以說是一個“拜金女”。我可以毫不避諱的告訴你我喜歡錢,當我還是一個高中剛畢業(yè)的小不點時,我沒有任何的經(jīng)濟來源...
    CC燦寶閱讀 219評論 0 1
  • 鑰匙去哪里了 周五的早上,學校一老師向我借圖書室的鑰匙,想去給孩子選幾本書,當我拉開放鑰匙的小格子的時候,心里一咯...
    河南鄭州毛秋風閱讀 212評論 0 0
  • 多少次想試著逃離的城市 離開時竟有點想念 我即將從一個車水馬龍的地方 回歸原始的鄉(xiāng)村生活 山間的鳥鳴代替了街頭的鳴...
    鐘春生的詩閱讀 177評論 0 2

友情鏈接更多精彩內(nèi)容