liveBook · Manning

Computed value

As explained in Building User-Friendly DSLs

A value specification that determines an attribute's value through an expression rather than by storing an initial value.

A computed value determines an attribute’s value from an expression instead of storing a fixed initial value. The attribute explicitly selects the value kind: initially or computed as. This distinction lets the runtime represent stored fields and derived values without ambiguity. section 11.1.1

Implementing computed values requires coordinated changes across the DSL, runtime generation, and expression handling:

  • Represent the attribute with a value expression and a value kind, replacing the separate initial value property. section 11.1.1
  • Detect computed attributes with a query such as isComputedFromExpression. section 11.4
  • Generate a getter for computed attributes and an initializer for ordinary attributes. section 11.4
  • Recursively translate expression nodes, including binary operations, into generated JavaScript. section 11.4

Rental price after discount

A rental price after discount can be declared as a computed attribute. Code generation emits a getter such as get rentalPriceAfterDiscount(), whose return expression evaluates the referenced price and discount. A binary operator of is translated into multiplication by 0.01 so a percentage discount is applied correctly. section 11.4

Listing 11.16 The classField template function
const classField = (attribute) => {
    const { settings } = attribute
    const value = settings["value"]
    const fieldName = camelCase(settings["name"])
    if (isComputedFromExpression(attribute)) {  #1
        return [  #2
            `get ${fieldName}() {`,
            `    return ${expressionFor(value)}`,
            `}`
        ]
    }
    return initializationFor(attribute)  #3
}

Inspect the classField template to see how computed attributes become getters while initially valued attributes retain initializer generation. section 11.4

How Building User-Friendly DSLs covers it

How deep it goes
Explains representation, migration, detection, getter generation, dependency traversal, and binary-expression translation.
Examples
Uses rental price after discount, percentage arithmetic, AST migration, and generated JavaScript getters as concrete artifacts.
What it assumes
Assumes familiarity with DSL attributes, runtime fields, AST objects, and JavaScript templates while clarifying initial-versus-computed values.
What you can do after
Build it from scratch by representing computed attributes, generating getters, and translating referenced expressions into JavaScript.
How it connects
Connects attributes with expressions, abstract syntax trees, code generation, getters, attribute references, and binary operations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building User-Friendly DSLs. The section links point to the parts of the book it draws on.