使用断言来验证函数参数是一种不好的做法吗?

时间:2017-05-02 19:49:18

标签: javascript node.js validation anti-patterns

我希望验证我得到的参数在给定一组情况下是有效的。特别是在生成SQL时,我想验证传递给函数的对象是否与服务器端同步或有效。

我想要解决的最自然的方法是使用以下

var InvalidIdValue = (actual) => return new Error(`Id: ${actual} is invalid. Expected id >= 1`)
var InvalidIdType = (actual, expectedType) => return new Error(`Id: ${typeof actual} is invalid. Expected ${typeof expectedType}`)

function sync(query, obj) {
    if(typeof obj.id != typeof 1) 
        return InvalidIdValue(obj.id)
    if(obj.id < 1)
        return InvalidIdValue(obj.id, 1)
    // Pull the data from server
}

但是使用断言,我可以将其缩短为

var assert = require('assert')

function sync(query, obj) {
    assert.ok(typeof obj == typeof 1 && obj.id > 0, 'Id needs to be an integer larger than 0')
    // Pull the data from the server
}

我不介意任何一条路线,但这样做是不好的做法?我之所以提出这个问题,是因为我认为断言仅适用于TDD。

谢谢:)

1 个答案:

答案 0 :(得分:1)

只要您将断言作为依赖关系,那么使用断言就没有错。从.ok运行的代码是一行,用于检查是否提供了真值。如果是假的,则调用.fail,这会引发相关的可记录信息错误。

编辑:

以下是函数.ok&amp;来自源代码的.fail

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;

// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.

function ok(value, message) {
  if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;