Chaining

Chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls of a structure. Each method returns a structure, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.

In order for this to work, the structure’s method needs to return the structure itself. For example (below), if we call the method add og container does’nt return anything, thus we cant chain further more.

typ continer[T: gen, G: int](): rec = {
    var collection: arr[G, T];
    var point: int = 0;

    fun add(val: T) = {
        if (point < G) {
            collection.push(val)
        } else {
            error = "some error"
        }
    } 

    fun add_2(val: T): Self = {
        if (point < G) {
            collection.push(val)
        } else {
            error = "some error"
        }
    }
}

var collection_1: continer[int, 5];
container_1.add(1).add(2)               //this throws an error, because first `add` returns none
container_1.add_2(1).add_2(2)           //this works, because `add` return the object itself

FOL, takes this into next level, in order to always work the chining (where it makes sense, of course) we uase double .. to indicate it..

typ continer[T: gen, G: int](): rec = {
    var collection: arr[G, T];
    var point: int = 0;

    fun add(val: T) = {
        if (point < G) {
            collection.push(val)
        } else {
            error = "some error"
        }
    } 
}

var collection_1: continer[int, 5];
container_1..add(1)..add(2)             //here now it works, eventhoug `add` does not retunr `Self`
                                        //because symbol `..` always reuturns the object itself from the
                                        //the method call, not the value

Method chaining eliminates an extra variable for each intermediate step. The developer is saved from the cognitive burden of naming the variable and keeping the variable in mind.

Method chaining has been referred to as producing a “train wreck” due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together.