4 ms·
Agree in general, but note that Java itself does not follow this rule: StringBuilder's and StringWriter's toString methods use toString for behavior — creating
by vlaaad 7y ago
Agree in general, but note that Java itself does not follow this rule: StringBuilder's and StringWriter's toString methods use toString for behavior — creating a string from accumulated chars, and I'm fine with that.
- nathanaldensr 7y agoThis also definitely does not apply to .NET where there are many classes that override ToString for meaningful, well-documented behavior (StringBuilder is one, funnily enough). It's best to check the docs or look at IntelliSense before applying this rule in a blanket fashion. That said, it does seem like Microsoft has since moved away from overriding ToString for such things. In all honesty, Object.ToString was probably a mistake to begin with.
- simendsjo 7y agoThere's nothing wrong with returning something well-specified from toString, but I agree this should never be relied upon. And even if toString actually return something well-specified, the same functionality should be available as a distinct method. Any form of (semi-)automatic SomeObject -> String should be treated as a convenience for the developer to avoid getting a non-descriptive memory location reported. Having the automatic toString isn't the problem, but maybe the name of the method is. It could be called "asDebugHelpRepresentation" or something more descriptive.
- asveikau 7y agoThe typical usage for StringBuilder tends to make it pretty obvious you're using a StringBuilder and everybody expects you will convert to a string at the end. Usually StringBuilders are short lived and all the calls and the declaration are close to each other.
- EpicEng 7y agoOk, but then the rule is not to use toString() for behavior unless it "makes sense" to do so, which is not a rule at all.
- asveikau 7y agoI think that misses my point. It's an established pattern recognizable to anyone who has read or written a lot of code. And locality of use and declaration is high. The danger of it being mixed up with another type in a refactor in faraway code is low. Whereas in the general case, where code can be sparse and types can be more freely altered, you could very easily change the type of something and not realize that a ToString() call on that type lurks somewhere else in the code base.
- Bartweiss 7y agoThis also goes for logging and even string-ification in a lot of popular Java libraries. It's certainly good to write methods like getName() if you foresee an issue with changes down the line, but precisely because toString is universal, it may well be invoked somewhere outside what you're writing.