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
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.
byte[] has two possible drawbacks:
Using a Stream can solve those problems. It depends on what data you're returning and what you expect users to do with it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With