Design by contract
solidity这门语言设计思路是什么?
什么是COP?
COP
面向条件的编程(COP)是面向合约编程的一个子域,作为一种面向函数和命令式编程的混合模式。COP解决了这个问题,通过需要程序员显示地枚举所有的条件。逻辑变得扁平,没有条件的状态变化。条件片段可以被正确的文档化,复用,可以根据需求和实现来推断。重要的是,COP在编程中把预先条件当作为一等公民。这样的模式规范能保证合约的安全。
post-condition
contract PostCheck {
uint public data = 0;
// Check that the 'data' field was set to the value of '_data'.
modifier data_is_valid(uint _data) {
_
if (_data != data)
throw;
}
function setData(uint _data) data_is_valid(_data) {
data = _data;
}
}
pre- and post-conditions
"_"
contract PrePostCheck {
uint public data = 0;
// Check that the input '_data' value is not the same as the value
// already stored in 'data'.
modifier data_is_valid(uint _data) {
if (_data == data)
throw;
_
}
// Check that the 'data' field was set to the value of '_data'.
modifier data_was_updated(uint _data) {
_
if (_data != data)
throw;
}
function setData(uint _data) data_is_valid(_data) data_was_updated(_data) {
data = _data;
}
}
FEATURES
- 函数主体没有条件判断
例子:
contract Token {
// The balance of everyone
mapping (address => uint) public balances;
// Constructor - we're a millionaire!
function Token() {
balances[msg.sender] = 1000000;
}
// Transfer `_amount` tokens of ours to `_dest`.
function transfer(uint _amount, address _dest) {
balances[msg.sender] -= _amount;
balances[_dest] += _amount;
}
}
改进后:
function transfer(uint _amount, address _dest) {
if (balances[msg.sender] < _amount)
return;
balances[msg.sender] -= _amount;
balances[_dest] += _amount;
}
COP的风格
modifier only_with_at_least(uint x) {
if (balances[msg.sender] >= x) _;
}
function transfer(uint _amount, address _dest)
only_with_at_least(_amount) {
balances[msg.sender] -= _amount;
balances[_dest] += _amount;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。