Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I prevent passing wrong number of parameters to methods with JS Lint, JS Hint, or some other tool?

I'm new to javascript programming (and scripting languages in general), but I've been using JS Lint to help me when I make syntax errors or accidentally declare a global variable.

However, there is a scenario that JS Lint does not cover, which I feel would be incredibly handy. See the code below:

(function () {
    "use strict";
    /*global alert */

    var testFunction = function (someMessage) {
        alert("stuff is happening: " + someMessage);
    };

    testFunction(1, 2);
    testFunction();
}());

Notice that I am passing the wrong number of parameters to testFunction. I don't foresee myself ever in a situation where I would intentionally leave out a parameter or add an extra one like that. However, neither JS Lint nor JS Hint consider this an error.

Is there some other tool that would catch this for me? Or is there some reason why passing parameters like that shouldn't be error checked?

like image 216
tandersen Avatar asked Jul 02 '15 22:07

tandersen


2 Answers

This is not generally possible with any static analysis tool. There are several reasons for this:

  • In general, JS functions can accept any number of arguments.
  • Most (all?) linters only work on a single file at a time. They do not know anything about functions declared in other files
  • There is no guarantee that a property being invoked as a function is the function that you expect. Consider this snippet:

    var obj = { myFunc : function(a,b) { ... } };
    var doSomething(x) { x.myFunc = function(a) { ... }; };
    doSomething(obj);
    obj.myFunc();
    

There is no way to know that myFunc now takes a different number of args after the call to doSomething.

JavaScript is a dynamic language and you should accept and embrace that.

Instead of relying on linting to catch problems that it wasn't intended to I would recommend adding preconditions to your functions that does the check.

Create a helper function like this:

function checkThat(expression, message) {
  if (!expression) {
    throw new Error(message);
  }
}

Then use it like this:

function myFunc(a, b) {
  checkThat(arguments.length === 2, "Wrong number of arguments.");

And with proper unit testing, you should never see this error message in production.

like image 83
Andrew Eisenberg Avatar answered Oct 03 '22 20:10

Andrew Eisenberg


It's not natively possible in javascript. You would have to do something like this:

var testFunction = function (someMessage) {
    var args = Array.prototype.slice.call(arguments);
    if (args.length !== 1) throw new Error ("Wrong number of arguments");
    if (typeof args[1] !== string)  throw new Error ("Must pass a string");
    // continue
};
like image 22
Ryan Wheale Avatar answered Oct 03 '22 18:10

Ryan Wheale