1

Consider the following function:

function interpolate(color1, color2, progress) {};

All arguments must be passed, color1 and color2 must be an instance of my color object and progress must be a number.

Is it faster to check the types or simply wrap a try/catch block round the logic and see if it fails?
If it does fail then I could check that all arguments are present and correct and throw a descriptive expection.

Jules
  • 4,319
  • 3
  • 44
  • 72
  • 4
    Putting a single try/catch around the function's logic seems to me to be asking for trouble; it will be difficult to isolate what the problem actually was. So "Is it faster ..." is probably the wrong question. It will be easier and more robust to check the arguments at the outset, and you probably shouldn't worry about speed unless you actually find that there's a performance problem in this part of your code. – Gareth McCaughan May 13 '12 at 22:02
  • My function is just an example but it could be used, say, in an animation routine and called multiple times per second. Now the overhead of checking the argument types versus the interpolation logic may be negligible but I've no idea unfortunately. – Jules May 13 '12 at 22:41

1 Answers1

2

I think it would be better to fail fast and do the checking up front as opposed to relying on a try/catch to catch incorrect parameters.

You can check that all arguments are passed by checking the length property of arguments and you can see how many parameters a function signature has by checking the length property of the function in question:

function interpolate(color1, color2, progress) {
    if (arguments.length !== arguments.callee.length) {
        throw "wrong number of arguments passed";
    }
};

Now it's a case of checking that color1 and color2 are objects of the type you expect and to check that progress is a number.

Community
  • 1
  • 1
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
  • 1
    `arguments.callee` isn't permitted in ES5 strict – Alnitak May 13 '12 at 22:17
  • good call, don't know if the OP is using strict mode. Replace `arguments.callee` with `interpolate` if you are. – Russ Cam May 13 '12 at 22:21
  • Since this isn't a generic check I may as well just check arguments.length !== 3? – Jules May 13 '12 at 22:35
  • Thanks for the links, though I can't believe the lengths one has to go to in the 1st one! Since I'm not interested in the class name, from what I can gather I can just use instanceOf myColorObject for the first two arguments. Is that correct? – Jules May 13 '12 at 22:38