NSData+Compression and API costs

21 Jul

During my Tinkering with CompressionLib series I built a small NSData extension (or category depending on your language of choice) to make compressing / decompressing data easier.

It had only two public methods:

func compressedDataUsingCompression(compression: Compression) -> NSData?

func uncompressedDataUsingCompression(compression: Compression) -> NSData?

I debated about adding initializers to the extension, but decided to hold off initially until I could give it some more thought.

It sounds trivial, but every bit of public API you expose is that much more you need to support. The cost of adding API isn’t really the code itself. Code is just one part. You have to consider the design, testing, documentation, maintainability, and support costs too.

What finally pushed me over the edge was reviewing NSData’s API.

NSData exposes convenience methods for initializing from the contents of a file

init?(contentsOfFile path: String)

And frequently when you’re dealing with compressed data it’s stored in a file on disk. So it seems only natural that you would expect to be able to both read it in and have it decompressed at the same time. After all, it is pretty unlikely that you’re going to read some compressed data into memory and leave it compressed.

So I added two convenience initializers to my NSData extension today.

convenience init?(contentsOfArchive path: String, usedCompression: Compression?)

Which returns a NSData object initialized by decompressing the data from the file specified by path using the given compression algorithm.

And the shorter “smarter” version

convenience init?(contentsOfArchive path: String)

Which returns a NSData object initialized by decompressing the data from the file specified by path. Attempts to determine the appropriate decompression algorithm using the path’s extension.

This method is equivalent to NSData(contentsOfArchive:usedCompression:) with nil compression

Here’s the repo for the Swift version.

Or, if you prefer, you can grab the Obj-C version here.