4

I've encountered multiple times where the coding of an object in a particular way may cause it to be in an inconsistent state. An example is this question.

From the answer: Using the decorator pattern to construct objects is bad because it leaves the object in an inconsistent state.

Can anyone please explain to me, with an example, what an object being in an inconsistent state really means?

Community
  • 1
  • 1
underdog
  • 4,447
  • 9
  • 44
  • 89

1 Answers1

4

Consider the below class which is the decorator class for InputStream. Here the close() method is left unimplemented. Now,if I create a object of this class and call close() on it, my assumption would be that the stream has been closed, but in reality,it isn't closed due to the incompletely implemented method close() in the decorator class.

 public class UnClosableDecorator extends InputStream {

    private final InputStream inputStream;

    public UnClosableDecorator(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public int read() throws IOException {
        return inputStream.read();
    }

    @Override
    public int read(byte[] b) throws IOException {
        return inputStream.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return inputStream.read(b, off, len);
    }

    @Override
    public long skip(long n) throws IOException {
        return inputStream.skip(n);
    }

    @Override
    public int available() throws IOException {
        return inputStream.available();
    }

    @Override
    public synchronized void mark(int readlimit) {
        inputStream.mark(readlimit);
    }

    @Override
    public synchronized void reset() throws IOException {
        inputStream.reset();
    }

    @Override
    public boolean markSupported() {
        return inputStream.markSupported();
    }

    @Override
    public void close() throws IOException {
        //do nothing
    }
}
Sagar D
  • 2,588
  • 1
  • 18
  • 31