Lazy loading in Javascript classes

2022-06-29T18:27:59.723738

While lazy loading vs eager loading comes up a lot in web development, I hadn't really thought about it in a more generic code context. The general idea is to only compute values when you need them. This can make a lot of sense if you have a class that is working with and returning a lot of possible data, but it might not need all of that data at the same time.

Let's say you had a class dealing with some data. This class can do a variety of manipulations of that data. You might be tempted to put all the transforms in the constructor.

class MyClass {
  constructor(data){
    this.data = data;
    this.someData = this.changeDataThisWay()
    this.otherData = this.changeDataThatWay()
  }

  changeDataThisWay() {
    return // transformed data
  }

  changeDataThatWay() {
    return // transformed data
  }
}

// initialize your class and get your data
const mine = new MyClass(data);
console.log(`${mine.someData} - ${mine.otherData}`);

However what if the developer using our class really only uses one data manipulation or the other, rather than both? We'll be computing data unnecessarily. Let's take another pass, where we only transform the data when the getter is called.

class MyClass {
  constructor(data){
    this.data = data;
  }

  get someData(){
    if (!this._someData) {
      this._someData = this.changeDataThisWay();
    }

    return this._someData;
  }
  
  get otherData(){
    if (!this._otherData) {
      this._otherData = this.changeDataThatWay();
    }

    return this._otherData;
  }

  ...
}