Mini-Pattern: The File / Stream Duality

by Charles Miller on June 11, 2004

Name: The File/Stream Duality

Context: Your API retrieves data from, or writes data to a file


  • The naive approach is to have the API take in a filename, or a File object to work on.
  • Far too many developers believe this is sufficient
  • Unless the file is random-access, then in order to read or write to that file, you're going to have to turn it into a byte stream.
  • One day, somebody is going to have a stream of bytes that is not a file, but that they want to pass through your API.
  • When that happens, this person will curse you, your parents, and the town you grew up in.


If you are writing an API that takes a filename, instead provide an API that does precisely the same thing to an arbitrary stream of bytes, and then add "convenience" methods that apply those stream-based methods to files.

Previously: The Need to Scribble

Next: Today's Horoscope