Question

I don't currently understand why I would choose to serialize an object instead of just doing a file output and then having a function read that file. What do I gain from serializing an object?

No correct solution

OTHER TIPS

You gain an industry-standard way of reading and writing an object's data, using a W3C approved data exchange format that has almost universal support for readers and writers in almost every programming language.

Serialization makes it easy to store the state of objects, and objects inside them (If they are Serializable and not marked as transient).

The benefits in your case :

Imagine you have a lot of different classes. Maybe coding a custom File-to-class parser is harder than readObject()

When you serialize an object, you are copying the actual byte data in memory into a stream. When you de-serialize that stream back into an object you get the identical object back including its internal object ID, which you would not get if you had written the properties of the object to a file, and then read it back in and interpreted it.

This means, if you serialize a collection of objects that reference each other, when you de-serialize them, they will still maintain their references to each other. This is good also for debugging a program. If an exception occurs you can create a memory dump on the users computer, and if they send it to you, then you can see directly what was in memory and the problems that may have been caused.

It is also easier to serialize a complex object with many properties to a stream than it is to build some string of representative data, which you will have to be read back, parse and construct a new object with it.

Really what you gain, is that it is easier/quicker and better for debugging.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top