Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to pass a stream around to multiple methods? [closed]

Tags:

c#

I have an interface defined as:

public interface IClientFileImporter
{
    bool CanImport(Stream stream);
    int Import(Stream stream);
}

The idea is to take any file stream and run it through a series of implementations of this interface to determine which one should handle the file. Some of the implementations may look for a certain header row, while others may look for a certain byte sequence, etc...

My question is, is it OK to pass a stream around like this as long as I never close it? Each method would have to be responsible for resetting the stream to position 0 if necessary, but are there any other potential issues (aside from thread safety)? This code really smells, IMO, but I'm not sure of a better way to do it.

like image 897
Chris Avatar asked Feb 28 '12 20:02

Chris


3 Answers

To prevent the underlying stream from being modified, create a wrapper stream that derives from Stream and forwards only safe calls to the wrapped stream. Also, don't assume the Import/CanImport methods reset the stream position. The caller of those method should reset the stream to a valid state before passing it to Import/CanImport.

like image 124
Andre Loker Avatar answered Nov 15 '22 01:11

Andre Loker


If each function returns the stream just the way it got it, I don't think there's a problem with it.

like image 27
zmbq Avatar answered Nov 14 '22 23:11

zmbq


This shouldn't be a problem.

Although I would probably restructure it slightly:

public interface IClientFileImporter
{
    int Import(Stream stream);
}

Then I would have the Import method return a -1 if it was not able to. Might make your other code a bit simpler.

like image 45
NotMe Avatar answered Nov 15 '22 00:11

NotMe