tags:

views:

905

answers:

13

Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.


EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

+16  A: 

No, the key is that you're supposed to override the default implementation of ToString() to make it useful. ToString() can be a great way to output the value of something back to the UI.

A simple example would be if you have a Name class with a three strings (First, Middle, Last). You can have a ToString() method that formats it for the UI: "Last, First Middle" for example.

Or a class that stores a mathematical operation (values Left=2, Right=3, Result=6 and an operator enum=Multiply). Call ToString() to get "2 * 3 = 6".

However, it is probably more common to have a variety of different To<qualifier>String() methods, like the .NET DateTime class. (ToShortDateString(), ToLongDateString(), ToLongTimeString(), ...)

Edit: As for why it's rooted at the Object class, it's simply because ToString() is a valid operation for anything.

Additionally, strings can be a good way of marshaling between data types or data consumers, because it's (practically) guaranteed to be parsable and doesn't require extra encoding or care.

lc
Very complete follow-up. I'm just thinking that the GUI-labeling stuff for toString() is overused. Why not something like `implements interface TextualRepresentation` or something like that?
Camilo Díaz
I do agree it's a valid operation for anything, but only from a programmer standpoint. My point is that there isn't any contract for specifying that the method should provide GUI-Friendly strings or expose the specific internals of the instance(fields), which are only useful for programmers, IMHO
Camilo Díaz
Often bad for UI purposes, as it doesn't take a user locale. Doesn't matter for debugging, does matter for end users.
MSalters
A: 

ToString() is also called by the .NET Framework implicitly when printing any object out to a string.

Console.WriteLine("My Object is" + object.ToString());

is equivalent to

Console.WriteLine("My Object is" + object);

because the ToString() is implicitly called.

I believe, though am not sure, that it is used by the debugger for the "value" of an object. This can be fairly handy, though limited. In most cases writing your own debugger visualizer would be a better idea.

Jeffrey Cameron
+9  A: 

toString() is useful whenever you want a string representation of an object. Naturally that happens for debugging purposes, but can also be valid to output results of operations to the user.

For example, let's say you have a Complex class which handles complex numbers. If you want to print them out to an user in a format like 3 + 2i, it is handy if they define toString() as you do not have to write the format every time and the output will be consistent. If you ever want to change that representation, for example to 3 + 2j, you only need to touch the toString() method in the Complex class.

So toString() is not for debugging purposes also, but is a good way to get consistent string representations of your objects.

Raim
Indeed, but no there is no guarantee of that `consistent string representation` at all.
Camilo Díaz
I got a FooFile class with FooFileSections. To write the file I just override ToString for the file itself: FooFile.ToString() as well as for each file section: FooFileSections.ToString(). then I build the file content by calling ToString in the right sequence for the FooFileSections, then just stream out the text. Probably not a good way overall, but quick and easy.
Glytzhkof
A: 

On AS3, I had to convert a 2D array into a 1D array. The fastest (run speed) and easiest (coding time) solution was:

var new1DArray:Array = the2DArray.toString().split(",");

Be surprised but it's actually working as intended and quite fast, too!

LiraNuna
+1  A: 

Useful for

  1. Gui (complex Property when you use PropertyGrid, Form header text)
  2. DataBinding (thats the way how it working)

And any other string output.

Avram
A: 

it might not be the "intented" use but I've used it for data serialization

storeToHardDrive(studentList.ToString());
Eric
+3  A: 

My personal preference is that toString() should never be used for anything other than debugging. If you want to produce a string for an object, provide a separate method that clearly documents your intent (getName(), getDescription(), etc). Never rely on the implementation of a toString().

The problem is that many developers see toString() as a debug-level string and think nothing of changing it (say when new fields are added or removed). Heck, some automated toString() builders use reflection to generate a toString() from the fields.

I've found this preference has served me well over the years.

Alex Miller
Given that The String is the most useful construct in programming, it can be extremely powerful to know that every object in your program space meets a contract to provide a string representation of itself. As with anything powerful, it can be abused, but it's a waste to avoid it.
Rex M
But given that the contract a) guarantees nothing about the format of the string and b) provides no symmetric api to convert from String back to the object, I find that it's a weak ass contract. I've debugged many problems that relate back to assuming a non-existent "contract" for toString.
Alex Miller
I have exactly the same view. I think the GUI label-textual representation stuff is just over-using the method.
Camilo Díaz
@Alex Miller - Totally agree. A string representation means nothing other than it should be human readable, and for any complex object, don't expect a pretty format, just functional for debugging.
Robin
A: 

I use ToString() a ton for datetime formats.

http://hunterconcepts.com/content/tools/formats/

hunter
A: 

Aside from what everyone else has already said, overriding ToString() is also useful when using controls that call it. For example, a ComboBox:

myComboBox.Items.Add(new MyClass());
// now, whatever ToString() returns is shown in the
// ComboBox, but you can get the object back by through
// the SlectedItem property.
Ed Swangren
+6  A: 

All I can say is that I have had code break when I changed the toString of my class to display some additional debug information.

The code in question was a GUI library that decided to use the value of toString as some internal thing (it was a couple of years ago... I forget what it was exactly). The end result was that I didn't use that library anymore.

I would say that since a large group of people see toString as being used for debugging (regardless of your opinion of what it you think it should be used for) that it is problematic to make use of the value returned from it to do anything programmatic (like parse it) or display it to a user.

If you are 100% in control of the toString methods then by all means do what you want.

So, to answer the question, no toString is not only useful for debugging, you can do anything you want with it. However, don't be surprised if toString changes in ways that make you unhappy.

TofuBeer
All I can say that beyond debugging, it's a very, very leaky abstraction :)
Camilo Díaz
+1  A: 

First, the toString method should return a human-readable textual representation of the object.

This issue is brought up in Effective Java as Item 10: Always override toString.

It references the Java API Specification for the Object.toString method:

The result should be a concise but informative representation that is easy for a person to read.

Aside from debugging, overriding the toString method of a class can be useful when ading objects into a JList or a JTable, which by default will use the toString method to display the object as a textual form in the list or table.

For example, in my case, I've overridden the toString method of objects that are added to a JList so that the user will be able to see information about the item in a list through the GUI.

So, there are indeed cases where the toString method is useful for cases other than debugging. The key is to have the toString method return information that is actually useful for a person to see, not the default Object.toString implementation where the object's memory location is used for its textual representation.

coobird
+3  A: 

In my experience, toString() has little value outside of debugging and logging. You cannot depend on it's format or contents over time, so other than being human readable, don't depend on it for anything other than the simplest of objects (such as the primitive object types). If there are multiple data members, expect they may change in type or number over time, and the output of the toString() along with it.

Another point I would like to strongly make. Do not call other methods in your toString(). Nothing worse than checking the variable contents on a breakpoint in the debugger, and then having more code execute because of method calls in the toString().

Robin
A: 

I think it's important to point out the the people who answered mentioning "toString" notice the lowercase "t" are generally talking about Java, and the people who answered mentioning "ToString" are generally referring to C#. Of course, this doesn't apply to all of the responses.

In my own observation (I use both daily), programmers in C# are encouraged to override "ToString" to display a useful textual representation. Whereas, in Java, I don't see this nearly as much. In fact, I rarely see this.

-JP

JP