I am designing the API for a client of a service that retrieves data as a stream of bytes.
What is the advantage of using
InputStream getData(String param1, String param2);
over
byte[] getData(String param1, String param2);
The method that returns the inputstream bothers me because
- now my code has to depend on external code to close the inputstream. I know that it is a best practice to close only those resources that you open so this seems wrong.
- The inputstream is not repeatable. Once the client of my code reads the stream the bytes are lost
- The stream in my implementation is actually over the network (socket). While I am using a connection pool and monitoring it to get rid of expired connections etc I feel it might be better to be able to close the resources I opened myself.
What’s the best way to design this? I even considered using
void writeData(String param, String param, OutputStream os);
but that makes the method name non-intuitive.
I’d return something like Guava’s
InputSupplier<InputStream>, which lets you request multiple distinct input streams.Additionally, Guava provides a number of methods which take an
InputSupplier<InputStream>, open an input stream, perform some whole-stream operation, and then close it without making you remember to close the input stream or whatever.Even if you don’t want to use Guava directly, it’s a nice technique that lets the client program decide how it wants to deal with it.