2. Materialized Derived Properties

Figure 14.2. A materialized derived attribute in a class diagram.

A materialized derived attribute in a class diagram.

If the value of a derived property is computed whenever there is a change in the value of one of the properties on which it depends, the derived property is called materialized. The value of such a materialized derived property is stored, and the getter method simply retrieves this stored value. When using JavaScript's get/set methods in an ES6 class definition, this means that we define a get method for initials retrieving the value of the internal attribute _initials, but no set method. The computation of the materialized derived property's value is performed in the setters of the attributes on which it depends, as shown in the following example:

var Person = class {
  constructor (slots) {
    // assign default values to mandatory properties
    this._firstName = "";  // string (non-empty)
    this._lastName = "";  // string (non-empty)
    this._initials = "";  // string (non-empty)
    // is constructor invoked with a non-empty slots argument?
    if (typeof slots === "object" && 
        Object.keys( slots).length > 0) {
      // assign properties by invoking implicit setters
      this.firstName  = slots.firstName ;
      this.lastName  = slots.lastName ;
    }
  }
  get firstName () {return this._firstName;}
  set firstName (f) {
    this._firstName = f;
    this._initials = this._firstName.charAt(0) + 
        this._lastName.charAt(0);
  }
  get lastName () {return this._lastName;}
  set lastName (l) {
    this._lastName = l;
    this._initials = this._firstName.charAt(0) + 
        this._lastName.charAt(0);
  }
  get initials () {return this._initials;}
}

Notice that the computation of the initials of a person is performed in the setters of firstName and lastName, whenever these attributes are initialized or changed.