Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of "object is in inconsistent state"

Tags:

java

object

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?

like image 540
underdog Avatar asked Aug 31 '25 23:08

underdog


1 Answers

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
    }
}
like image 128
Sagar D Avatar answered Sep 03 '25 14:09

Sagar D