dimanche 10 juillet 2022

How to handle invalidated object / object invalidation safely?

Builder pattern is can be used to handle validation of object like this:

class WebSocketConnectionBuilder {
    constructor(public readonly url: string) {

    }
    connect(): Promise<WebSocketConnection> {
        const ws = new WebSocket(this.url);

        return new Promise((solve, reject) => {
            ws.onopen = () => {
                solve(new WebSocketConnection(ws));
            }
            ws.onerror = (error) => {
                reject(error);
            }
        });
    }
}

It is safer than normal WebSocket object, because we can assure that connection has been established when we have WebSocketConnection object. We can validate the fact "the connection is established" from presence of WebSocketConnection object.

However, when this connection closed, I can't invalidate WebSocketConnection object to make be not able to use it. Once the object created, the object become valid permanently on perspective of type system. What I can do is just "throw error" when method about connection called in wrong time(i.e. connection closed).

I'm sorry to be not able to describe what exactly I want to do, but I'll be thankful to any answer or idea of safer way to invalidate object. Any programming language is ok.

Aucun commentaire:

Enregistrer un commentaire