Skip to content

Instantly share code, notes, and snippets.

@e7h4n
Created August 29, 2011 03:09
Show Gist options
  • Save e7h4n/1177700 to your computer and use it in GitHub Desktop.
Save e7h4n/1177700 to your computer and use it in GitHub Desktop.

何为契约式设计 (Design by Contract)

在面向对象编程中,复用性是非常重要的概念。为了保证各个模块的高度复用性,我们需要一个系统的方法来描述模块以及模块在系统中的关系。比如每个模块的说明文档,指出了模块的输入格式输入格式,就是这样一种系统的方法。契约式设计也提供了这样一个系统的方法,在契约式设计的理论中,一个软件系统被视为一组相互交流的部件,它们之间互动的基础是一组准确定义了的规范,它规定了这些部件相互之间的义务 -- 即契约。

例子

这里将以一个普通的除法函数作为开始,一步步的说明如何在 JavaScript 里面使用契约式设计。

/**
 *@method divide
 *
 *@param {Number}a
 *@param {Number}b
 *@return {Number}
 */
function divide (a, b) {
    if (typeof a !== 'number') {
        throw new Error('a must be a number');
    }

    if (typeof b !== 'number') {
        throw new Error('b must be a number');
    }

    if (typeof b === 0) {
        throw new Error('divide zero');
    }

    return a/b;
}

以上函数通过 jsdoc 注释声明了契约。契约的前置条件为函数参数都必须是数字且第二个参数必须不为 0,后置条件为返回一个数字。函数的 9-15 行验证了这一前置条件。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment