views:

88

answers:

4

I'm writing a class interface that needs to return references to binary files. Typically I would provide a reference to a file as a file path. However, I'm considering storing some of the files (such as a small thumbnail) in a database directly rather then on a file system. In this case I don't want to add the extra step of reading the thumbnail out of the database onto the disc and then returning a path to the file for my program to read. I'd want to stream the image directly out of the database into my program and avoid writing anything to the disc unless the user explicit wants to save something.

Would having my interface return a FileStreamor even a Imagemake sense? Then it would be up to the implementing class to determine if the source of the FileStream or Image is a file on a disc or binary data in a database.

public interface MyInterface
{ 
    string Thumbnail {get;}
    string Attachment {get;}
}

vs

public interface MyInterface
{ 
    Image Thumbnail {get;}
    FileStream Attachment {get;}
}
+2  A: 

You could return a Stream object that streams to either a file or a database

thecoop
+1  A: 

You could use a byte[] to represent the file if its size is not very big and fits into memory. Otherwise a Stream is good but make sure you implement IDisposable to release it properly.

Darin Dimitrov
The largest any of the known files will be is ~200kb. Attachments could be anything but I could limit them to a maximum size.
Eric Anastas
+2  A: 

You can. However I would change the interface to look more like:

public interface MyInterface
{ 
    Image CreateThumbnail();
    FileStream CreateAttachment();
}

This resolves any ambiguity about the lifetime of the returned objects; keeping them from being disposed out from under you for instance.

dkackman
A: 

For small content where the usage is clear like a thumbnail I think you would be better off returning the type as it will be used (i.e. Image). If you've got large content where the purpose may vary or they may be reasons to read it partially then Stream is they way to go. In either case the source of the content is hidden from the user of the class. You will also want to consider the dispose semantics of the stream and whether or not you want the user of the class to have control over how long a database connection stays open.

jdasilva
Why a Stream over a FileStream?
Eric Anastas
It abstracts away the source of the content from the caller. This is especially useful if the stream might be different sources like a file or some sort of database blob. It could also be a MemoryStream. Say you originally started with a some sort of database blob stream and then decided to read the entire blob first, you could switch to a MemoryStream with no impact to the caller. In general, I always use a Stream unless there is a need for the caller to know what type of stream it is. (And I can't recall a case where that was true at least in my code.)
jdasilva