Abort in constructor

Viewed 28

In JavaScript and/or TypeScript, what is the common approach to solving the following problem?

Assume we have a class whose constructor depends on some operation. If that operation fails, the instance should not be created.

Example:

class Item {

    constructor(itemId) {

        // Try to get the data for the passed-in item id
        const itemData = itemDataMap.get(itemId);

        // If the item data was found
        if (itemData) {
            // Great, continue to init the instance as normal...
        }
        else {
            // Problem: We can't init the instance without the item data.
            // Hence we don't want to return an instance.
            // What should we do here?
        }
    }
}

Solutions I can think of include trying to return an empty object, or throwing an error. But is there a common/preferred approach?

1 Answers

Personally I like having pure constructors without any side-effects. You just pass data and it creates you object. It so much easier to use, test and debug.

And if you wish to have side-effect (like validation, data fetching), create static function on the object that will be responsible for that.

One more nice thing is that you can convert that function to async function without any issue (constructors can't be async).

class Item {
  constructor(data) {
    //...
  }

  static create(id) {
    if (id === 1) {
      throw new Error("my error")
    }
    return new Item({
      id
    })
  }
}


console.log(Item.create(2))
console.log(Item.create(1))

Related