Functions
A function declaration describes an operation: its name, its inputs and what it returns. A BHaus function has no body in the programming sense; there is no code inside. It can describe the body's intent in prose, which is what a code generator or a person implementing it reads.
Declaring a function
A top-level function begins with FUNCTION, followed by
a name, a parameter list in
parentheses and an optional return type after a colon:
FUNCTION calculateTotal(values: Array[Integer]): Integer
The return type is optional. Leave it off for an operation that produces nothing:
FUNCTION logEvent(message: String)
By convention a function name starts with a lower-case letter, which sets it apart from the upper-case type names around it.
Parameters
Each parameter takes one of two forms and a single list may mix them:
- a named parameter,
identifier: Type, when the name adds meaning; - a bare type, just a
Type, when the type alone says enough.
FUNCTION transfer(from: Domain/Account, to: Domain/Account, Integer): Boolean
Here from and to are named because those words carry meaning. The third parameter
is a bare Integer, the amount, where a name would add nothing. Commas separate
parameters and the types can be anything, including
composite types like ?Array[String].
Functional intents
A declaration gives a function's shape. A functional intent gives its purpose.
An intent is a single line beginning with > that describes what the body should do:
FUNCTION calculateTotal(values: Array[Integer]): Integer
> sum every element of the array
> return the sum
A high count suggests that the function or method is too large. Move some of its behaviour into one or more additional functions or methods.
A functional intent MUST be written in imperative mood.
Use commands like "return", "calculate", "validate" rather than present-tense descriptions like "returns" or "calculates".
For example: use > return true if valid not > returns true if valid.
An intent attaches to a body, meaning a function or a method.
It differs from a comment (which starts with #).
Functions inside types
The FUNCTION keyword is only for standalone functions at the top level. When an
operation belongs to a STRUCT, PROTOCOL or
CLASS, it becomes a method and drops the keyword. The visibility and
the parentheses are enough to mark it as callable:
PROTOCOL Shape:
PUBLIC area(): Float # a method, with no FUNCTION keyword
Methods take the same parameters, return types and functional intents as standalone functions.