Behavioral Attributes: pure
Explore the concept of pure functions in D programming, understanding how they avoid mutable global state and side effects. Learn the compiler's role in enforcing purity, how pure functions optimize code by caching, and the special considerations for templates, debug mode, and member functions.
We'll cover the following...
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 ...