new instantiation design alternatives

Mark S. Miller erights at google.com
Fri Sep 12 08:18:17 PDT 2014


Even when written explicitly, either by an IDE or a human, the

constructor(a, b, c) {
    this = new super(...arguments);
    ...
}

pattern is usually bad. It is fine in a certain special case I mention
below. It would be a disaster to have this pattern be the default smoothed
over by a syntactic shortcut. Here's the problem:

----- at time v1 -----
class Point {
    constructor(x, y)
        this.x = x;
        this.y = y;
    }
    equals(otherPt) {
        return this.x === otherPt.x && this.y === otherPt.y;
    }
}

class ColoredPoint extends Point {
    constructor(x, y, color) {
        this = new super(x, y);
        this.color = color;
    }
    // whether we override equals here is not the issue
}

---- at later time/revision v2 ----
class Point {
    constructor(x, y, fudgeFactor = 0.000001) {
        this.x = x;
        this.y = y;
        this.fudgeFactor = fudgeFactor;
    }
    equals(otherPt) {
        return abs(this.x - otherPt.x) <= fudgeFactor &&
                abs(this.y - otherPt.y) <= fudgeFactor;
    }
}
--------

Under normal circumstances, as shown above, this is a valid evolution of
the Point class, even without examining or revising existing clients like
ColoredPoint. Since the Point constructor had only two non-optional
parameters, it could normally assume that existing clients had only called
it with two arguments. Thus, it would normally be assumed compatible with
existing clients to add new optional arguments. Passing all arguments by
default breaks this assumption, making the "fragile base class" problem
much worse.

The special case where the super(...arguments) is ok, even needed, is when
the base class constructor already has a rest parameter.

EIBTI applies forcefully here.

-- 
  Cheers,
  --MarkM
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140912/da8c6202/attachment.html>


More information about the es-discuss mailing list