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

Is using assertions to validate function parameters a bad practice?

我希望验证我得到的参数在给定的一组情况下是否有效。特别是在生成 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。

谢谢:)

只要您同意将断言作为依赖项,使用断言就没有错。来自 .ok 的 运行 代码是检查是否提供真值的一行。如果为假,它会调用 .fail,它会抛出一个带有相关的可记录信息的错误。

编辑:

以下是源代码中的函数 .ok.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;