Robert

15%
Flag icon
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 is recommended that you do this for value classes, such as phone number or matrix. The advantage of specifying the format is that it serves as a standard, unambiguous, human-readable representation of the object. This representation can be used for input and output and in persistent human-readable data objects, such as CSV files. If you specify the format, it’s usually a good idea to provide a matching static factory or constructor so ...more
Robert
tl;dr: Please err on _not_ using toString() for data exchange (whether file/CSV, API response, or database storage), except for few exceptions. Instead, expect that your intended audience of the string is developers (i.e., technical, non-user human working under the hood). Note: This is the 2nd edition of this comment (on the 3rd edition of this book) =). You can see my 1st edition of this comment (on the 2nd edition of this book) here: https://www.goodreads.com/notes/22719418-effective-java/74-robert/93bf3bdf-e20d-4e72-b471-5401411c3ead. Let's start by pointing out that there are three possible audiences for this string: End users, Machines (i.e., data exchange with other code), and Developers (debugging). * End-Users*: toString() is insufficient for preparing a string for display to users, since it cannot reasonably adapt to context; it lacks a good mechanism for formatting for locale, for content around it (e.g., tense, pluralization, etc.), etc.. *Machines, data exchange*: There can easily be a variety of places the string needs to be sent to: file/disk, over the wire (possibly to a variety of clients), or database. Each may want/expect a different format; e.g., ISO 8601, or Unix Timestamp. Even this phone number example is a case-in-point why: There isn't a single phone number format, even in the US. Should you add — do all of your clients expect— the '+1' country code? So, it's best to create explicit methods for each format — better yet, separate the formatter from the object (i.e., create a class or utility method for formatting the data for your use case; like DateFormat). In other words, End-Users and Machines need/deserve something more flexible and predictable than toString(), and why make toString() this thing that might sometimes be tailored to either of those, and sometimes not, and even then perhaps often still not what they need? So, just make toString always tailored for developers to aid in debugging. Among the exceptions are those objects that represent things that are strings by definition, that have only one well-defined, correct string representation. An example of that are URIs; a string-based specification for resource identification.
Effective Java
Rate this book
Clear rating
Open Preview