Java toString for debugging or actual logical use

This can be a very simple question, apologies if this has already been asked. If toString () in Java is used for real program logic or is it only for debugging / reading only for people. My main question is to use toString () or write another method called asString () when I need to use a string representation in the current program stream.

I ask a question: I have a bunch of classes in a web service that rely on toString () to work correctly, in my opinion, something like asString () would be safer.

thanks

+6
source share
2 answers

Except in a few specific cases, toString should be used for debugging, and not for production data flow.

The method has several limitations that make it less suitable for use in the production data stream:

  • Without accepting any parameters, this method does not allow you to easily change the presentation of a string in response to the environment. In particular, it is difficult to format the string so that it is sensitive to the current language.
  • Being part of the java.Object class, this method is usually overridden by subclasses. This can be harmful in situations where you are dependent on a particular idea, because the authors of the subclass may not have an idea of ​​your limitations.

The obvious exceptions to this rule are the toString methods of StringBuilder and StringBuffer , because these two methods simply make an immutable string from the mutable contents of the corresponding object.

+8
source

This is not only for debugging / reading only people, it really depends on the context in which the object is used. For example, if you have a table that displays some X object, then you might want the table to display a readable textual representation of X, in which case you usually use the toString () method. This, of course, is a basic example, but there are many uses, in this case the implementation of toString () would be a good idea.

+1
source

Source: https://habr.com/ru/post/957844/


All Articles