Effective Java 2.0_ Chinese-English control _item 10__java

Source: Internet
Author: User
Tags assert readable sprintf string format

Article Author: Tyan
Blog: noahsnail.com |  CSDN | Jane book item10:always override ToString

While Java.lang.Object provides a implementation of the ToString method, the string, which it returns is generally not what The user of your class wants to. It consists the class name followed by a "at" sign (@) and the unsigned hexadecimal representation of the hash code, F or example, "phonenumber@163b91." The general contract to ToString says that the returned string should is "a concise but informative representation that I s easy for a person to read [JavaSE6]. While it could was argued that "phonenumber@163b91" was concise and easy to read, it isn ' t very when informative to "(707) 867-5309." The toString contract goes on to say, "It is recommended ' all subclasses override ' this method." Good advice, indeed!

Although Java.lang.Object provides an implementation of the ToString method, it usually returns a string that is not intended by the user who uses the class. The returned string contains the class name followed by a hexadecimal representation of the @ symbol plus the hash code, such as phonenumber@163b91. The General Convention for ToString states that the return value should be "concise but readable information representation" [JavaSE6]. Although phonenumber@163b91 can be considered concise and readable, it is not rich in information compared to (707) 867-5309. The ToString Convention further states that "all proposed subclasses override this method." It's really a good suggestion.

While it isn ' t as important as obeying the equals and hashcode contracts (item 8, item 9), providing a good toString I Mplementation makes your classmore than pleasant to use. The ToString method is automatically invoked as an object is passed to println, printf, the string concatenation Operato R, or assert, or printed by a debugger. (The printf method being added to the platform in release 1.5, as were related methods including String.Format, which is Rou ghly equivalent to C ' s sprintf.)

Although it is not as important as adhering to the Equals and Hashcode conventions (item 8, item 9), providing a good ToString implementation can make your class more comfortable to use . The ToString method is automatically invoked when an object is passed to println,printf, the string concatenation operator, or assert, or when printed through the debugger. (The platform in the Java 1.5 version adds a printf method, including String.Format, similar to the sprintf method in C).

If you ' ve provided a good toString to phonenumber, generating a useful diagnostic message is as easy as this:

If you have provided a good ToString method for PhoneNumber, it is easy to generate useful diagnostic information:

System.out.println ("Failed to connect:" + PhoneNumber);

Programmers'll generate diagnostic messages in this fashion whether or don't you override the But messages ' t be useful unless to do. The benefits of providing a good toString method extend beyond instances of the class to objects containing to These instances, especially collections. Which would you rather the when printing a map, "{jenny=phonenumber@163b91}" or "{jenny= (707) 867-5309}"?

Whether or not you rewrite the ToString method, programmers generate diagnostic information in this way, but unless you rewrite the ToString method, the information is useless. The advantage of providing a good tostring method is that, in addition to instances of the class, the objects that contain references to these instances, especially collections, are extended. Which one do you prefer {jenny=phonenumber@163b91} or {jenny= (707) 867-5309} When printing a map?

When practical, the ToString method should return all of the interesting information contained in the object, as in th E Phone number example just shown. It is impractical if the "object is large" or if it contains state "is not" conducive to string representation. Under these circumstances, toString should return a summary such as "Manhattan White Pages (1487536 listings)" or "thread[ Main,5,main] ". Ideally, the string should be self-explanatory. (The Thread example flunks this test.)

when practiced, the ToString method should return all the interesting information contained in the object, as shown in the example of the phone number just now . Overriding the ToString method is impractical if the object is large or it contains a state that cannot be represented by a string. In this case, ToString should return a summary information, such as Manhattan White Pages (1487536 listings) or Thread[main,5,main]. Ideally, the string should be self explanatory. (The thread example does not meet this requirement.) )

One important decision you'll have to make when implementing a toString method is whether to specify the format of the return value in the documentation. It's recommended that's for value classes, such as phone numbers or matrices. The advantage of specifying the format is it serves as a standard, unambiguous, human-readable representation of the Object. This representation can is used for input and output and in persistent human-readable data objects, such as XML documents. If you specify the format, it's usually a good idea to provide a matching static factory or constructor so programmers CA n easily translate back and forth between the object and its string representation. This approach was taken by many value classes in the Java platform libraries, including BigInteger, BigDecimal, and most of The boxed primitive classes.

One of the important decisions you make when implementing ToString is whether to specify the format of the return value in the document. It is recommended that you do this for value classes, such as phone numbers or matrices. The advantage of specifying the return value format is that it provides a standard, clear, readable representation of the object. This representation can be used in input and output, or in a consistent, readable data object, such as an XML document. If you specify a format, it is usually a good idea to provide a matching static factory or constructor, and the programmer can easily switch back and forth between the object and its string representation. Many value classes in the Java Platform Library Use this method, including Biginteger,bigdecimal and most basic types of wrapper classes.

The disadvantage of specifying the format of the "ToString return value is" that once your ' ve specified it, you ' re stuck with It for life, assuming your The class is widely used. Programmers'll write code to parse the representation, to generate it, and to embed it into persistent data. If you change the representation in a future release, you'll break their code and data, and they'll yowl. By failing to specify a format, your preserve the flexibility to add information or improve the format in a subsequent Ase.

The disadvantage of specifying the ToString return value format is that once you specify it, assuming that your class is widely used, you must always stick to it. The programmer will write code to translate the representation, produce this format and embed it in the persisted data. If you change the presentation format in a future release, you will break their code and data and they will complain. If you do not specify a format, you retain the flexibility to add information or improve the format in subsequent versions.

Whether or not you decide to specify the format, you should clearly document your intentions. If you are specify the format, you should does so precisely. For example, here's a toString method to go with the PhoneNumber class in Item 9:

Whether you decide to specify a format or not, you should clearly indicate your intention. If you specify a format, you should do it exactly. For example, the ToString method for PhoneNumber classes in the following item 9:

/**
    * Returns The string representation of this phone number.
    * The string consists of fourteen characters whose format
    * is ' (XXX) yyy-zzzz "where XXX is the area code, YYY is
  * the prefix, and ZZZZ is the line number.  (Each of the
    * Capital letters represents a single decimal digit.)
    *
    * If any of the three parts of this phone number are too small
    * to fill up their field, the field is padded with l eading Zeros.
    * For example, if the value of the line number are 123, the last * four characters of the string representation would be "01 23 ". *
    * note ' There is a ' separating the closing s* parenthesis after the ' area ' code from the '
    Igit of the * prefix.
*/
@Override public String toString () {return
       String.Format (%03d)%03d-%04d, AreaCode, prefix, linenumber );
}

If you are decide to specify a format, the documentation comment should read something as this:

If you do not specify a format, the document comments should read as follows:

/**
* Returns A brief description of this potion. The exact details * of the representation are unspecified and subject to change, * but the following may be regarded as Ty  Pical:
*
* "[Potion #9: Type=love, Smell=turpentine, Look=india ink]" *
   /@Override public String toString () { ... }

After reading this comment, programmers who produce code or persistent data that depends on the details of the format would Have no one but themselves to blame then the format is changed.

Programmers who write code or persist data that relies on format details, after reading this document, can only be responsible for the consequences once the format changes.

Whether or not, specify the format,* provide programmatic access to all of the information contained in the value retur Ned by Tostring*. For example, the PhoneNumber class should contain accessors for the "area" code, prefix, and line number. If you are fail to does this and you are force programmers who need this information to parse the string. Besides reducing performance and making unnecessary work for programmers, this process was error-prone and results in Fragi Le systems that break if you change the format. By failing to provide accessors, your turn the string format into a de facto API, even if you ' ve specified that it ' s SUBJEC T to change.

Whether you specify a format or not, you should provide a program Access interface for all the information contained in the ToString return value . For example, the PhoneNumber class should contain an accessor for the region code, prefix, and line number. If you do not, you will force the programmer who needs this information to take the conversion of this string. In addition to reducing efficiency and creating unnecessary work for programmers, this process is prone to error and can cause the system to be very vulnerable if you change the format system to crash. If the accessor is not provided, even if you indicate that the string format is changeable, the string format becomes the actual API.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.