Immutability Is Hard
public final class Bytes { final byte[] bytes; public Bytes(byte[] original) { int size = original.length; this.bytes = new byte[size]; System.arraycopy( original, 0, this.bytes, 0, size); } public byte byteAt(int index) { return bytes[index]; } public int size() { return bytes.length; } ...
I need to write the bytes to an OutputStream
in a couple places, so I added a method which does just that:
public void writeTo(OutputStream out) throws IOException { out.write(bytes); }
Did you catch my mistake?
writeTo()
exposes our internal byte[]
to user code making our class not so immutable. For example, zeroing out the internal bytes is now as easy as:
Bytes bytes = ...; bytes.writeTo(new OutputStream() { @Override public void write(byte[] bytes) { Arrays.fill(bytes, 0); } ... });
To make our class immutable again, we must modify writeTo()
to copy the bytes into a temporary buffer first, and then pass that buffer to the OutputStream
.
It's times like this that I wish Java had immutable arrays (with runtime checking). Maybe I'll see what we can do about that...