assert instruction

The assert instruction is used to document and ensure that a given condition is always true at the moment of execution.

If the condition is violated at runtime, then a program error is thrown immediately. Hence assert supports the 'Fail fast!' principle and helps in debugging.

For example assert can be used to state a loop invariant (a predicate that holds for every iteration of the loop) or to state that a given object reference doesn’t point to null.

The assert keyword is followed by a boolean expression that represents the condition. It can optionally be followed by a message clause that defines a customized error message which is displayed in case of violation of the condition at runtime.


function assert_demo

    // Note: The 'string' function 'find_first' returns the position
    // of the first occurrence of a substring
    // if the substring doesn't exist it returns 'null'

    const dot_position = "/path/to/file.txt".find_first ( "." )
    assert dot_position is not null \
        message: "The file path is supposed to contain a dot."
    write_line ( dot_position.to_string )
The condition checked in an assert instruction must not have side effects. It’s evaluation can consume time and memory, but must not change the behavior of the program.

results matching ""

    No results matching ""