I develop a game library in javascript, containing many classes. I hesitate on the behavior that I should follow concerning method parameter validation:
Should I check the validity of parameters passed to each method ?
By example, when a method take only a number between 0 and 100 in parameter, should I check that the value is correct?
I have dozens of classes, each with dozens of methods. For a simple getter, I can have more than half lines code only used for checking parameters. Add checks makes my code less maintainable, more heavy.
Seeing that it’s a library, destined to be used by many other programmers, checking parameters can avoid many mistakes and bugs, and would be a appreciated.
So, how do other javascript libraries, handle this and what is the best solution?
2
Validate anything that you might consider “suspect”, i.e. anything that comes from outside your own class. Parameters to public methods? They come from “Outside” so validate them. Parameters to private methods? Technically these are already “Inside” so there’s less reason to do it again. (Of course, you might be checking for different criteria at this level, so you might still have Good Reason to do so).
And have a consistent means of handling parameter “problems”. Some people like to throw Exceptions, others return null values from their methods. YMMV. Pick what works for you and stick with it.
Yes, you should always validate your inputs. Not validating is one of the primary sources of unexpected behaviour.
Without knowing the structure of your code, if you have a bunch of simple methods and one core method you could put your validation code in the main method rather than all of the individual ones.
As you say it is a library, developers will do their own validation based on their business logic. Their business logic may be different from yours.
A quick flick through the jQuery source sees them validating input parameters.
4