使用断言来validation函数参数是一个不好的做法吗?

我正在寻找validation,我得到的参数是什么是有效的给定的一组情况。 特别是在生成SQL时,我想validation传递给函数的对象与服务器端是同步的还是有效的。

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

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的。

谢谢 :)

只要你可以断言是一个依赖关系,那么使用assert没有任何问题。 从.ok运行的代码是一行,用于检查是否提供了真值。 如果是虚假的,它会调用.fail ,这会导致相关的可logging信息出错。

编辑:

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