The samples in question are c#, but it applies to any language.
If you have a function which reads content from a stream. Who should be responsible for ensuring that the stream position is correct before reading?
The caller, or the function doing the reading?
e.g.
Caller positions the stream:
public byte[] ReadBytesFromStream(Stream inputStream)
{
using (var ms = new MemoryStream())
{
inputStream.CopyTo(ms);
return ms.ToArray();
}
}
public void DoThingWithStream(Stream stream)
{
// .. do some stuff
stream.Position = 0;
var bytes = ReadBytesFromStream(stream);
// .. do some more stuff
}
Reader positions the stream:
public byte[] ReadBytesFromStream(Stream inputStream)
{
inputStream.Position = 0;
using (var ms = new MemoryStream())
{
inputStream.CopyTo(ms);
return ms.ToArray();
}
}
public void DoThingWithStream(Stream stream)
{
// .. do some stuff
var bytes = ReadBytesFromStream(stream);
// .. do some more stuff
}
The reader positioning the stream means that I can call the function over an over again with the same stream and get the same bytes out.
The caller positioning the stream means that
- It's a little more work to set up and if you're throwing the stream around a lot there may be a lot of re-positioning going on. But,
- I could use the same reader function to read from an arbitrary point in the stream if I really wanted to.
I've pretty much convinced myself that the caller should do the positioning, but if that's the case then are there any circumstances when it shouldn't?