0

Is a "wrong" to return anything else besides this in a constructor?

Take this TypeScript Queue sample:

class Queue {

    private buffer: string;

    constructor(buffer: string = "") {
        this.buffer = buffer;
    }

    push(n: string): Queue {
        return new Queue(this.get() + n);
    }

    get(): string {
        return this.buffer;
    }

    print() {
        console.log(this.buffer);
    }
}
new Queue().add("1").add("2").add("3").print(); // prints 123

Everytime push is called, a new Queue instance is created. And in a child class i would like to prepend a suffix in the queue like this.

class QueuePrefix extends Queue {
    constructor() {
        super();
        return this.push("q:");
    }
}
new QueuePrefix().add("1").add("2").add("3").print(); // prints q:123

However I must return the result from the function push, instead of 'this'.

Is this an acceptable strategy?

5
  • Does it work: to return an object in the constructor?
    – Erik Eidt
    May 10, 2021 at 22:00
  • @ErikEidt: JavaScript is its own beast. Yes this works. You can return any kind of object you want from a constructor. TypeScript may impose additional restrictions, though. May 10, 2021 at 22:42
  • 4
    You never update the buffer which seems odd. Instead of returning something different from the constructor you could add it to this.buffer. It looks to like you added a new level of wtfness to an already questionable design. It violates POLA. Disclaimer: I am not a script guy. The fact that return is not really a thing in script land, that you are really just pushing more stuff into the same pipeline, has bitten me more than once. May 11, 2021 at 5:19
  • 1
    @MartinMaat this looks like a good answer to me.
    – Christophe
    May 11, 2021 at 7:22
  • 1
    super is just a way to refer to the constructor of the superclass, it's used like any other method call, you can pass parameters to it. Your Queue constructor already takes a single parameter that lets you set the initial buffer value, so you can just do super("q:"). May 11, 2021 at 11:08

1 Answer 1

3

I don't think it is wrong per se, as long as the returned object is a subtype of the expected type. But returning anything else would certainly violate the principle of least surprise.

In your particular case I don't see why it is necessary though, you could just initialize the buffer in the constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.