1.前提
这是Bertrand Meyer在EL语言中提出的一个设计风格,流行了近20年。不过现在比较少用,不是很流行了,主要原因在下面提出
2.什么是契约式设计
契约式设计就是按照某种规定对一些数据等做出约定,如果超出约定,程序将不再运行,例如要求输入的参数必须满足某种条件
在scala中常用require和assume等
class BankAccount(val balance: Double) {
require(balance >= 0.0)
def debit(amount: Double) = {
require(amount > 0.0, "The debit amount must be > 0.0")
assume(balance - amount > 0.0, "Overdrafts are not permitted")
new BankAccount(balance - amount)
}
def credit(amount: Double) = {
require(amount > 0.0, "The credit amount must be > 0.0")
new BankAccount(balance + amount)
}
}
3.目前在Test-Driven Development (TDD)用得比较多,很少带进主code中
4.缺点就是A drawback of using these methods and Ensuring is that you can’t disable these checks
in production也就是在生产中无法自由地把这些契约disable
5.真要引入这种风格到你的code时,得编写一个模块来随时关闭这种功能
最后
以上就是苹果超短裙最近收集整理的关于Design By Contract(契约式设计)的全部内容,更多相关Design内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复