Table of Contents
- Item 85. Prefer alternatives to Java serialization
- Item 86. Implement Serializable with great caution
- Item 87. Consider using a custom serialized form
- Item 88. Write readObject methods defensively
- Item 89. For instance control, prefer enum types to readResolve
- Item 90. Consider serialization proxies instead of serialized instances
Item 85. Prefer alternatives to Java serialization
Prefer alternatives to Java serialization
Serialization is risky because it expands the attack surface. The best way to avoid that risk is to deserialize nothing. If you must use it, apply object deserialization filtering.
Item 86. Implement Serializable with great caution
Implement Serializable with great caution
Making a class serializable is simple: implement Serializable.
But the tradeoff is significant. The class takes on security and maintenance risk and loses extensibility.
Item 87. Consider using a custom serialized form
Consider using a custom serialized form
An ideal serialized form should represent only logical state, independent of physical implementation.
If a class implements Serializable and uses default serialization,
the serialized form becomes coupled to the current implementation.
Item 88. Write readObject methods defensively
Write readObject methods defensively
readObject is effectively another public constructor.
Treat it with the same rigor as constructors.
Validate arguments and defensively copy mutable parameters.
Item 89. For instance control, prefer enum types to readResolve
For instance control, prefer enum types to readResolve
A singleton design can break as soon as it implements Serializable.
Whether you avoid default serialization or provide readObject explicitly,
you may lose instance-count guarantees. Using enum preserves invariants safely.
Item 90. Consider serialization proxies instead of serialized instances
Consider serialization proxies instead of serialized instances
Implementing Serializable introduces ways to create instances outside constructors.
That increases bug and security risk. The serialization proxy pattern significantly reduces that risk.