This suggestion comes from Joshua Bloch's "Provide Programmatic Access to All Data Available in String Form ". I wrote this short article based on his outline.
This suggestion means that if you write a module, the data information that can be disclosed in the module should be provided to the customer in String format. If you do not provide such a String access interface, the customer who uses this module may feel inconvenient to obtain information about this module. Even worse, he may parse the String information he can get. Most of the time, this String is fromToString ().
He gave an example of j.Ava. lang. Throwable. getStackTrace ().
Public class throwable {<br/> Public stacktraceelement [] getstacktrace (); <br/>}< br/> Public final class stacktraceelement {<br/> Public String getclassname (); <br/> Public String getfilename (); <br/> Public int getlinenumber (); <br/> Public String getmethodname (); <br/> Public Boolean isnativemethod () <br/>}
HereGetstacktrace ()Is a good example. When you captureThrowable(GenerallyException).Getstacktrace ()GetStacktraceelementArray, and then the exception details are displayed in the form of a String in a loop. The customer can also useStacktraceelementFor eachStacktraceelementTo obtain information. If you do not have thisGetstacktrace ()The user needsPrintstacktrace ()Parsing detailed information about exceptions is really painful. UseTostring (), You have a try. It can only display the information of the elements at the top of the current stack.
Here I think it is worth emphasizing two places: one is "All" in "All Data Available" and the other is "Available ". Let's talk about All first, because you can't assume that your customer code will never access a certain data, so we need to provide All the data information, that is, the + method. Besides, Available means to minimize access permissions. This is also a principle of OO, and this is a method. For example, we all knowArraylistIs implemented by an array, and the actual size of this array is smaller than or equalSize (). Do you want to provide the length of this array? Of course not, because this is notListInterface requirements,ArraylistUsers do not need to care about it either.
Looking at the code you have previously written, ah, many do not follow this rule. Some write all the information to tOstring ()So that the customer code needs to parse tOstring (). Some of them are even written.Tostring ()It does not cover all public information. A lot of information is parsed in the Customer Code. Such a String is usually for people to see, so such painful code is used when writing logs. When they want to print the object information in the log, get this field, get that field, and then judge that the logic finally forms a String. This was originally the responsibility of this class.