As comments have shown, there is no strict specific way to decide the contents of your toString
method. But to help you decide, keep in mind the three general scenarios where you examine an object’s details:
- Minute detail, looking at any of the various values within an object. For this you are likely deep in a debugging session in which case you are using the powerful debugger tooling found in today’s IDEs.
- Summary presentation to the user. This should generally be designed for localization requiring a
Locale
. For this, notice how some classes offer a getDisplayName
method. For example, java.time.DayOfWeek
.
- Identifying an object briefly, for messages in logging, and for quick dumps to the console for testing or for sanity-checks while developing. This is the main use for
toString
in my experience.
So I suggest including only enough detail in your toString
method as needed to identify the object with certainty. For example, UUID or sequential ID fields. And fields like “Student ID”, “Employee ID”, “ Invoice Number”, and such.
Perhaps include a few extra fields to get a sense of the data. Those few extra fields might be the ones you are likely to search and sort on.
Omit more trivial fields which are likely to be of little interest during most of your development, testing, and logging.
Most importantly, consider the sensitivity of your data. The toString
method tends to be called from many places, quite often, and quite casually. While many of those calls are ephemeral, calls to toString
for logging in particular may result in data being written in plain text to files that may be quite long-lived. So I would recommend omitting the fields that may be sensitive, private, or have security implications.
Note that in Java 16+, a class defined as a record automatically gets a default toString
implementation provided implicitly by the compiler. That default implementation includes all the fields you specified for your record. For a record with many fields, or with sensitive fields, you may choose to provide your own custom implementation of toString
.