3 ms·
So what's the solution to deserialization? He mentioned the Even class, but there didn't seem to be anything that looked to fix the lack of validation when rea
by yarg 4y ago
So what's the solution to deserialization?
He mentioned the Even class, but there didn't seem to be anything that looked to fix the lack of validation when reading from JSON?
If it's out of scope, why bring it up without mentioning further work (or am I missing something)?
- mrkeen 4y ago(My words, not the article's) The fix is to go through the front door, not the back door. Whatever deserialisation library/technique you use, it should have to use constructors just like everyone else, because that's where you can put your logic to make sure all your invariants hold.
- gizmo686 3y agoThe problem is Java's Serializable interface, which is a core part of the language. To the extent that it is implemented with VM black magic, and has an entire keyword (transient) in the languages syntax to support it. It is possible to provide your own (de)serialization logic, and so you could, in principle, enforce your invariant there. Unfortunately, to provide custom logic you implement: private void writeObject(ObjectOutputStream) private void readObject(ObjectInputStream) Notably, the deserialization method is not a constructor, which causes problems if you have final fields. You can use the defaultReadObject method to invoke the JVM black magic, then perform your own invariant checks, but you need to know to do this. When the alternative of adding 'implements serializable' you will likely have developers forget that they need to add the checks. On the glass half full side, at least classes need to opt in to serializeability. There is another universe, where classes are serializable by default. Having said all of this, Java's serializable is a massive security hole that should never be given untrusted input.
- tadfisher 3y agoThe solution is code generation, which is more performant and less brittle than maintaining runtime reflection machinery to break encapsulation. Moshi is a good example of a library that does this.