Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java toString for debugging or actual logical use

Tags:

java

This might be a very basic question, apologies if this was already asked. Should toString() in Java be used for actual program logic or is it only for debugging/human reading only. My basic question is should be using toString() or write a different method called asString() when I need to use the string representation in the actual program flow.

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

Thanks

like image 308
jack_carver Avatar asked Nov 11 '13 16:11

jack_carver


People also ask

What is a toString method in Java used for?

The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.

Does Java automatically use toString?

Every class in Java inherits the default implementation of the toString method. The functionality of the toString method is to return a String representation of the object on which it's called.

Should you always override toString?

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.

Is toString required for all classes?

This is how every class has a toString() method: since Object has a toString() method, then 'children' of Object inherit a toString() method, the children of children of Object inherit a toString() method, and so on. So every class 'automatically' gets a toString() method by inheritance.


1 Answers

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

The method has several limitations which make it less suitable for use in production data flow:

  • Taking no parameters, the method does not let you easily alter the string representation in response to the environment. In particular, it is difficult to format the string in a way that is sensitive to the current locale.
  • Being part of the java.Object class, this method is commonly overridden by subclasses. This may be harmful in situations when you depend on the particular representation, because the writers of the subclass may have no idea of your restrictions.

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

like image 159
Sergey Kalinichenko Avatar answered Oct 25 '22 23:10

Sergey Kalinichenko