on
Pure procedures in Fortran
In Fortran, a keyword I haven’t used enough so far is PURE. We want functions but also many subroutines to avoid side-effects. To ensure this, Fortran let us add the keyword PURE in front of a procedure declaration in order to tell the compiler that it does not contain any side-effect.
As I keep forgetting the list of things to avoid in a PURE procedure, I write them down here in order to find them quickly too. Acccording to Wikipedia, the procedure should:
- alter no global variable,
- perform no I/O,
- contain no saved variables (i.e. no SAVE attribute),
- not alter any of its arguments if the procedure is a function.
The first point is easy to tackle, in the idea that global variables should be used for constants (to avoid magic numbers for example), or in some rare occasions.
The second one avoids debugging with print statements. However, we can either remove the PURE keyword when debugging, or use unit tests.
The third one is not that difficult too, as the SAVE attribute can either be avoided with another design for the procedure or put in a wrapper subroutine for example.
The last one can be summarized by declaring all the variables as INTENT(IN).
To me, this appears more as common sense than restrictive conditions. At least, with the statement, the compiler can help us writing better code. I still need to find the exhaustive list of the conditions for a pure procedure, though.