Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a public API method return InputStream or byte[]

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

  1. 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.
  2. The inputstream is not repeatable. Once the client of my code reads the stream the bytes are lost
  3. 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.

like image 915
subodh Avatar asked Feb 21 '12 22:02

subodh


2 Answers

byte[] has two possible drawbacks:

  • You have to store everything in memory at once - which could be problematic if you are manipulating a lot of data.
  • Users of your class will have to wait for all of the data to be available - it is not possible to start processing as soon as some data is available. This can be a significant disadvantage if the network is slow.

Using a Stream can solve those problems. It depends on what data you're returning and what you expect users to do with it.

like image 128
ARRG Avatar answered Sep 19 '22 01:09

ARRG


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.

like image 22
Louis Wasserman Avatar answered Sep 17 '22 01:09

Louis Wasserman