Tuesday, 2 May 2017

Is using assertions to validate function parameters a bad practice?

I am looking to validate that the parameters I am getting are what is valid given a set of circumstances. Particularly with generating SQL, I want to validate that an object passed to a function is in sync, or is valid, with the server side.

The most natural way I want to approach this is using the following

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
}

But using assertions, I can shorten this to

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
}

I don't mind either route, but is it a bad practice to do this? My reason for the question is because I have it in my mind that assertions are intended for TDD only.

Thanks :)



via Jonathan Schmold

No comments:

Post a Comment