Search code examples
blockchainassertonflow-cadence

In Cadence smart contract programming language, what distinguishes pre/post conditions from assert statements?


Pre and post-conditions are considered pure conditions, as they prohibit any state mutative operations. Similarly, assert statements also do not allow state mutative operations.

However, there remains a key distinction between the two. As a developer, it is important to understand the circumstances under which pre/post conditions are more suitable than assert statements for a given function. Are there any implications on gas, accessibility, or other factors to consider?


Solution

  • Conditions and assertions have some similarities, but also some differences:

    • Both conditions and assertions evaluate an expression and abort execution if the condition is false
    • Currently, both conditions and assertions may have be impure. In the upcoming Stable Cadence release, conditions have to be "view" (see https://forum.onflow.org/t/another-update-on-stable-cadence/3715)
    • Conditions are declarative, and allows the easy declaration of what the function expects (pre-condition) and what the function guarantees (post-condition).
    • Assertions may appear at any point in the function, whereas conditions may only be pre or post conditions, i.e. are executed at the beginning or end of the function
    • Post conditions are executed at every exit point of a function. Ensuring an assertion is executed at every exit point, when the function has multiple exit points, often leads to code duplication.
    • Post conditions may refer to values of expressions at the beginning of the function using the special before(...) function
    • Conditions may appear in interfaces (!). This allows the establishment of requirements for all implementations of the interface. See https://en.wikipedia.org/wiki/Design_by_contract