Search code examples
javascripttypescriptes6-class

set class' private members to constructor arguments


class Foo {
  #one
  #two
  #three
  #four
  #five
  #six
  #seven
  #eight
  #nine
  #ten
  #eleven
  #twelve
  #thirteen
  #fourteen
  #fifteen
  #sixteen

  constructor(
    one,
    two,
    three,
    four,
    five,
    six,
    seven,
    eight,
    nine,
    ten,
    eleven,
    twelve,
    thirteen,
    fourteen,
    fifteen,
    sixteen
  ) {
    this.#one = one;
    this.#two = two;
    this.#three = three;
    this.#four = four;
    this.#five = five;
    this.#six = six;
    this.#seven = seven;
    this.#eight = eight;
    this.#nine = nine;
    this.#ten = ten;
    this.#eleven = eleven;
    this.#twelve = twelve;
    this.#thirteen = thirteen;
    this.#fourteen = fourteen;
    this.#fifteen = fifteen;
    this.#sixteen = sixteen;
  }
}

What's a solution to this (anti?) pattern?


Solution

  • Having 16 arguments is no fun for anyone looking to use your constructor. The configuration object idea that you raised in comments is much more interesting, certainly when you combine it with the idea to have one private property of type object that has all these properties. Then you can use Object.assign to have it updated with the user's preferences:

    class Foo {
      #options = {
        one: 1,
        two: 2,
        three: 3,
        four: 4
      }
      constructor(options = {}) {
        Object.assign(this.#options, options);
        console.log(this.#options);
      }
    }
    
    let foo = new Foo({three: 3000});