Constructors should assign parameters before generated values

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the object-oriented-programming category.

Last Updated: 2024-04-26

I had this code and it failed:

class StripeIntegration {
  constructor(
    stripe: Stripe
  ) {
     this.elements = this.addStripeElementsFieldsForCreditCard;
     this.stripe = stripe;
  }

  addStripeElementsFieldsForCreditCard() {
    // BOOM: It refers to `this.stripe`, which wasn't assigned yet
    const elements = this.stripe.elements();
  }
}

The issue was that I referred to this.stripe in the addStripeElementsFieldsForCreditCard method before assigning the stripe constructor parameter to this.stripe.

The fix assigns stripe before calling the method that consumes it:

class StripeIntegration {
  constructor(
    stripe: Stripe
  ) {
     this.stripe = stripe
     this.elements = this.addStripeElementsFieldsForCreditCard
  }
}

Lesson

Here's a prospective rule: "anything passed into a constructor MUST be assigned before anything generated within methods of the instance gets assigned".