Chris said:
Perhaps. I tend to see this as too leaky to be worthwhile. You're
impacting a lot of code in order to build something that doesn't provide
any additional guarantees. After all, ArrayList implements Serializable
yet can't guarantee that it can be serialized.
I did say I wanted to "improve the likelihood" of being able to
serialize instances, not that I wanted to ensure successful
serialization. If the approach I describe were ubiquitous then it would
be much more effective.
Worse, though, you impact client code here as well. There are plenty of
good reasons to hold references to objects that you know are
serializable, and yet not use a serializable type. For example, I often
keep references of type List for obvious reasons, yet List does not
extend Serializable. I may need to add casts to my code in order to use
an API that uses Serializable as a type, and yet there's no good way
that I could modify my code to hold variables of type Serializable in
the first place.
I disagree. For a class whose instances are expected to routinely be
serialized, declaring method parameters to be Serializable both
reinforces the point with the class' users and provides some degree of
compile-time checking. It is incorrect to keep references of a
non-Serializable type and nevertheless expect the referenced objects to
be Serializable, even if you "know" that they really are, just as it is
incorrect to keep references of type Collection and yet assume that the
referenced objects are Lists. Indeed, the error is precisely in relying
on knowledge about the objects' classes that is not reflected in their
references' declared types. Typecasts (of reference types) are usually
a sign of this kind of error, with the only exception I can think of
being casting to disambiguate an overloaded method invocation.
By the way, the type safe solution in the List example is not to cast,
but rather "new ArrayList<SomeSerializableType>(myAnyList)".
(Aside: avoiding most need to engage in the kind of incorrect coding
discussed above is by far my favorite aspect of both generics and
covariant return types.)
In the end, I dismiss use of Serializable as a type as being without
significant merit. If it could make serialization safe, of course, that
would be phenomenal... but it can't. Instead, it only adds more static
hurdles to using what is ultimately a runtime-checked feature anyway.
No, it can't make serialization safe, because serialization is
fundamentally unsafe. I remain convinced, however, that it makes
serialization saf*er* -- by making some of the class' expectations
explicit in its structure -- and, moreover, that it presents no
additional hurdle whatsoever to otherwise typesafe code.