Function

Synchronous

Function is used to set up operations for updating states of objects as we normally implement. In this section, we also point out another aspect of functions. Functions can be treated as Models.

Let's say we have a top-level function and its usage:

int add(int a, int b) => a + b;

void main() {
    final a = add(1, 2); // 3
    final b = add(3, 4); // 7
    final c = add(5, 6); // 11
    final d = add(7, 8); // 15
}

The function add can be considered as a Model. This is because of the fact that it maintains immutability.

add(1, 2) will always return 3 no matter where the function is called, and the same applies to other parameter combinations. We can imagine that add can be converted into a Model like this:

Class Add {
    final a1and2 = 3;
    final a3and4 = 7;
    final a5and6 = 11;
    final a7and8 = 15;
    ... // and so on
}

That means this type of function can be transferred and processed as data without worrying about state mutation.

To be considered as a Model, the function needs to be independent from any mutable elements in its body.

/// Function as valid model
int add(int a, int b) => a + b;

int variable = 2;

/// Function as invalid model.
/// If the [variable] is changed, the result of the function will be affected.
int add(int a, int b) => a + b + variable;

Asynchronous

So how should asynchronous functions be treated? They can be treated as stateful objects, similar to a unit. Refer to Stateful Operation.