Behavioral Attributes: pure

Get acquainted with the pure behavioral attribute of functions.

pure functions

As you have seen in the functions chapter, functions can produce return values and side effects. When possible, return values should be preferred over side effects because functions that do not have side effects are easier to make sense of, which in turn helps with program correctness and maintainability.

A similar concept is the purity of a function. Purity is defined differently in D than most other programming languages. In D, a function that does not access a mutable global or static state is pure.

Since input and output streams are considered as mutable global state, pure functions cannot perform input or output operations either.

In other words, a function is pure if it produces its return value and side effects only by accessing its parameters, local variables, and immutable global states.

An important aspect of purity in D is that pure functions can mutate their parameters. Additionally, the following operations that mutate the global state of the program are explicitly allowed in pure functions:

  • Allocate memory with the new expression

  • Terminate the program

  • Access the floatingpoint processing flags

  • Throw exceptions

The pure keyword specifies that a function should behave according to those conditions, and the compiler guarantees that it does so. Naturally, since impure functions do not provide the same guarantees, a pure function cannot call impure functions.

The following program demonstrates some of the operations that a pure function can and cannot perform:

Get hands-on with 1000+ tech skills courses.