4 ms·
> And a debugger would call it by default. But a debugger is far from the only time you want to output a debug representation. A properly formatted log message
by josefx 2y ago
> And a debugger would call it by default.
But a debugger is far from the only time you want to output a debug representation. A properly formatted log message is the most common case I deal with and one where you can generally use String manipulation freely without fear of breaking anything important.
> This would also make the purpose explicit in the code.
So you made the debug output explicit and verbose, but left toString() a mess that according to you will at least be used for "user-level" messages, JSON and "whatever", which are completely distinct use cases that have nothing in common other than that they output a string as a result. Worse, trying random string operations on a JSON output can break the JSON, so your list of example use cases for implicit string conversion already favors brittle stringly typed code.
> (for example, with safely escaped control characters or additional meta-data).
That assumes the class knows exactly how it is going to be displayed. Which only works if you have a well defined debugger interface for that. At which point you are probably better of dropping the stringly typed code and provide the debugger with a type safe interface for its output, especially since you mention "meta-data".
> This is all a symptom of the same method being used for different purposes.
And your "solution" does nothing to fix that. You might be better of killing toDebugString and toString entirely instead of turning one not so great API into two completely arbitrary and just as bad APIs and force people to roll their own. At which point people trying to output an object for anything will have to chain dozens of instanceof checks to see which kind of String representation the object supports, making the language worse to use.