Unfortunately, in JavaScript, switching from a constructor or class to a factory is a breaking change
JavaScript Factory Functions vs Constructor Functions vs Classes
Eric Elliott
1.7K28

Sorry, but that’s nonsense.
It broke because you didn’t refactor properly.

It’s fine to discourage people from using classes, but please don’t make up incorrect examples to prove your point.

These are mistakes that people who knows JavaScript don’t make, or at least knows how to fix.

Some points to make here:

  • Using a method definition syntax makes your function unconstructable. This is not we want if we need to maintain a backwards-compatible API.
  • Since we’re in constructor mode now, `this` refers to the created object. We can’t have `this` refer to AutoMaker object. No one uses `this` to access static properties, so no one would write `this.bundle` anyway. That’s why I think this example is flawed.
  • Constructors in JavaScript, unlike in other languages, may return an arbitrary object. This means you can return a pooled instance, a subclass instance, or a completely unrelated object.

But something will break with this approach:

  • instanceof checks will fail. This is the only breaking change I can think of, but that’s the problem of an instanceof operator. But it’s been a general guideline to avoid `instanceof` even in Java world. Has nothing to do with classes!

Still, there are ways to switch to factories while retaining the API.

For example, you can create a class that proxies calls to the instance created by the factory. But it’s a fixable problem.

class CarProxy {
constructor () {
this._car = factoryCar()
}
drive () {
return this._car.drive()
}
}

No need to force any change on the callers.

You may argue that it’s more work to maintain a class-based API. And that’s right. That would be a valid reason to prefer factories — not “it’s a breaking change,” backed with an invalid example.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.