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.
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.
If each function returns the stream just the way it got it, I don't think there's a problem with it.
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.
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