Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net streams: Returning vs Providing

I have always wondered what the best practice for using a Stream class in C# .Net is. Is it better to provide a stream that has been written to, or be provided one? i.e:

public Stream DoStuff(...)
{
    var retStream = new MemoryStream();
    //Write to retStream
    return retStream;
}

as opposed to;

public void DoStuff(Stream myStream, ...)
{
    //write to myStream directly
}

I have always used the former example for sake of lifecycle control, but I have this feeling that it a poor way of "streaming" with Stream's for lack of a better word.

like image 887
Daniel Park Avatar asked Mar 22 '15 21:03

Daniel Park


1 Answers

I would prefer "the second way" (operate on a provided stream) since it has a few distinct advantages:

  • You can have polymorphism (assuming as evidenced by your signature you can do your operations on any type of Stream provided).
  • It's easily abstracted into a Stream extension method now or later.
  • You clearly divide responsibilities. This method should not care on how to construct a stream, only on how to apply a certain operation to it.

Also, if you're returning a new stream (option 1), it would feel a bit strange that you would have to Seek again first in order to be able to read from it (unless you do that in the method itself, which is suboptimal once more since it might not always be required - the stream might not be read from afterwards in all cases). Having to Seek after passing an already existing stream to a method that clearly writes to the stream does not seem so awkward.

like image 128
ChristopheD Avatar answered Sep 30 '22 20:09

ChristopheD