Fwd: Re[2]: Towards better serialization

Michał Kłeczek michal at kleczek.org
Thu Jun 13 06:22:33 UTC 2019


Hi Brian,

Sorry for multiple posts - my mail client got confused with headers
and subject lines - changed it now, hope it helps.

------ Original Message ------

>
>>you want to serialize those data.
>>You cannot be more decoupled than current serialization as it is purely
>>declarative.
>
>Really?
>
>The mechanisms serialization gives you to control serialization are readObject, writeObject, readResolve, writeReplace, etc.  Which are all purely imperative -- and couple state extraction / reconstruction with stream reading and writing.
>
>As a bonus, if you implement readObject (and any class with invariants must, or else it is broken),

Not really:
1. It depends on the use case - in some of the use cases a class
author can simply assume the state is valid after deserialization
(similar to what happens when you hibernate/resume your laptop or take
a virtual machine snapshot and recreate it on another machine) -
paradoxically this strategy seems to be more secure than implementing
custom readObject() as witnessed by many deserialization gadgets with
broken readObject() implementation.
2. You can implement writeReplace()/readResolve() pair (which is
exactly what is in the proposal + some syntactic sugar).
3. You can provide an invariant check method which would be called by
the deserialization framework after the object is reconstructed (which
I have done several times by overriding
ObjectInputStream.resolveObject())

>you have to validate the arguments explicitly in readObject, and as a bonus, you get to do it in a completely different way than you do in the constructor.
But - as I said in my first e-mail - *forcing* developers to implement
writeReplace()/readResolve() pair (adding some syntactic sugar on top)
is throwing the baby out with the bathwater.

Why don't we simply make it easier to implement post-deserialization
invariant checks? There is ObjectInputValidation interface - but its
usage is so obscure that I have never seen it used.
It can be as easy as adding a default method to Serializable:

public Serializable {
public default void readObjectValidate() throws InvalidObjectException {}
}

Simple, effective and backwards compatible.

--
Michal


More information about the amber-dev mailing list