Table of Contents


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.

Choose alternatives such as JSON instead of Java serialization.



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.

Declaring Serializable is simple, but the cost is real.



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.

Design a custom serialized form that correctly describes the object.



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.

Handle readObject methods carefully.



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.

Use enum types when controlling instance count to preserve invariants.



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.

Serialization proxy pattern enables safer invariant-preserving serialization.