Chapter 14. Derived Properties

Table of Contents

1. Virtual Derived Properties
2. Materialized Derived Properties
3. Dealing with Derived Properties in the User Interface

In certain cases, a property may have the only purpose to provide some information that is computed from other information items. For such a derived property, there is no point to allow the user entering a value for it. Examples of derived properties of a class Person are the attributes age and initials. The value of age is computed on demand from the value of the attribute dateOfBirth and the current year. The value of initials is computed from the values of the attributes firstName and lastName.

Unlike in the case of standard properties, the value of a derived property cannot be set by the user. Rather, it is computed from the values of other properties. Consequently, it does not have a setter, but only a getter method.

1. Virtual Derived Properties

Figure 14.1. An example of a virtual derived attribute in a class diagram.

An example of a virtual derived attribute in a class diagram.

When the value of a derived property is computed on demand, only, by its getter method performing its computation, the derived property is called virtual. The value of such a virtual derived property is not stored. When using JavaScript's get/set methods in an ES6 class definition, this means that we only define a get method for age, but no internal property like _age, and no set method:

var Person = class {
  constructor (slots) {
    // assign default values to mandatory properties
    this._name = "";  // string (non-empty)
    this._dateOfBirth = 0;  // Date
    // 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.name = slots.name;
      this.dateOfBirth = slots.dateOfBirth;
    }
  }
  get name () {return this._name;}
  set name (n) {this._name = n;}
  get dateOfBirth () {return this._dateOfBirth;}
  set dateOfBirth (d) {this._dateOfBirth = d;}
  get age () {
    var today = new Date();
    return today.getFullYear() - this.dateOfBirth.getFullYear();
  }
}