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.
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:
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:
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.
Since derived properties are not set by user input, there are no input
, but only output
fields for them in a user interface. This is illustrated in the following example of an HTML form: