0

I'm writing classes work like FilterInputStream or FilterOutputStream.

Looks like

public FilterReadableByteChannel implements ReadableByteChannel {

    // Should I permit null for channel?
    public FilterReadableByteChannel(final ReadableByteChannel channel) {
       // ...
    }
}

And I found that both FilterInputStream and FilterOutputStream permit null source.

 * @param   in   the underlying input stream, or <code>null</code> if
 *          this instance is to be created without an underlying stream.

Question:

  1. Is there any practical reason for this?
  2. Is there any possible case that changing the underlying source after created?

I know that Why Not? could be an answer, but I want to know if there were any reason why the original API designer did this.

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

2

Is there any practical reason for this?

Yes. Even if not declared as such, classes Filter*Stream are conceptually abstract classes. IOW, they only exist to be extended. Subclasses could need to provide the in or out parameters after construction (example: lazily; on first real use), and Filter*Stream gives them this flexibility.

Is there any possible case that changing the underlying source after created?

The obvious case is when source is initially null. Other cases that come to my mind are: 1. Creating a subclass of Filter*Stream that acts as a selector. IOW, has several underlying streams and methods to switch from one to the other. 2. Creating a subclass of FilterInputStream that concatenates different InputStreams. 3. Creating a subclass of FilterOutputStream that splits output into different OutputStreams.

I know that Why Not? could be an answer, but I want to know if there were any reason why the original API designer did this.

Yes: generality.

Mario Rossi
  • 7,651
  • 27
  • 37