在Cadence智能合同编程语言中,预/后条件与断言语句的区别是什么?

huangapple go评论49阅读模式
英文:

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?

答案1

得分: 3

条件和断言有一些相似之处,但也有一些不同之处:

  • 条件和断言都评估一个表达式,并在条件为假时中止执行。
  • 目前,条件和断言都可以是不纯的。在即将发布的 Stable Cadence 版本中,条件必须是“视图”(请参阅 https://forum.onflow.org/t/another-update-on-stable-cadence/3715)。
  • 条件是声明性的,并允许轻松声明函数期望的内容(前置条件)和函数保证的内容(后置条件)。
  • 断言可以出现在函数的任何地方,而条件只能是前置条件或后置条件,即在函数的开始或结束执行。
  • 后置条件在函数的每个退出点执行。确保在函数有多个退出点时,在每个退出点执行断言通常会导致代码重复。
  • 后置条件可以使用特殊的 before(...) 函数引用函数开始时的表达式值。
  • 条件可以出现在接口中!这允许为接口的所有实现建立要求。请参阅 https://en.wikipedia.org/wiki/Design_by_contract
英文:

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

huangapple
  • 本文由 发表于 2023年3月7日 00:41:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定