Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we validate method arguments in JavaScript API's?

I'm developing a JavaScript library that will be used by 3rd party developers. The API includes methods with this signature:

function doSomething(arg1, arg2, options)

  • arg1, arg2 are 'required' simple type arguments.
  • options is a hash object containing optional arguments.

Would you recommend to validate that: - argument types are valid? - options attributes are correct? For example: that the developer didn't pass by mistake onSucces instead of onSuccess?

  • why do popular libraries like prototype.js do not validate?
like image 826
Totach Avatar asked Nov 12 '09 15:11

Totach


People also ask

What do you validate in API?

Validation can mean a lot of things, but in API land it generally means figuring out if the data being sent to the API is any good or not. Validation can happen in a lot of different places - it can happen on the server, and it can happen in the client.

Which are the correct input restrictions used for validation purpose?

Validation-related attributesThe value must be greater than or equal to the value. There must be a value (if set). Unless the step is set to the any literal, the value must be min + an integral multiple of the step. The number of characters (code points) must not be less than the value of the attribute, if non-empty.


2 Answers

You have the right to decide whether to make a "defensive" vs. a "contractual" API. In many cases, reading the manual of a library can make it clear to it's user that he should provide arguments of this or that type that obey these and those constraints.

If you intend to make a very intuitive, user friendly, API, it would be nice to validate your arguments, at least in debug mode. However, validation costs time (and source code => space), so it may also be nice to leave it out.

It's up to you.

like image 94
xtofl Avatar answered Oct 30 '22 02:10

xtofl


Validate as much as you can and print useful error messages which help people to track down problems quickly and easily.

Quote this validation code with some special comments (like //+++VALIDATE and //--VALIDATE) so you can easily remove it with a tool for a high-speed, compressed production version.

like image 41
Aaron Digulla Avatar answered Oct 30 '22 03:10

Aaron Digulla