-
Notifications
You must be signed in to change notification settings - Fork 155
Description
This is a high-level (but low-priority) design issue, aiming at a possible refactoring, only to make the code a bit nicer.
Right now, there are many places where certain arrays are validated, and the pattern that frequently appears is (in pseudocode):
const theArray = someObject.theArray;
if (defined(theArray)) {
if (!BasicValidator.validateArray(...)) {
result = false;
} else {
for (let i=0; i<theArray.length) {
if (!SpecificValidator.validateElement(... theArray[i]...)) {
result = false;
}
}
}
}
It first checks the array with BasicValidator.validateArray, which makes sure that the object...
- is defined
- is an array
- has the expected (minimum/maximum) length
- contains elements of a certain (basic) type (like
numberorobject)
If this succeeds, it checks all array elements, often with very specific validation routines for the respective type.
There are some 'configurations' that appear frequently. For example:
"Check that something is an array with length of at least 1, and contains numbers in [0, n]"
(for example, for any sort of "index arrays").
For these cases, further convenience functions could be added in the BasicValidator, like
BasicValidator.validateIndicesArray(..., minNumElements, maxValuePerElement, ...)
But even for the more general case, there's a pattern that could be carved into code. This could probably a function that accepts some sort of "element validation callback", with the goal of writing the above pseudocode (which in reality, carries a few more lines of boilerplate code) as something like
if (!Magic.validateArray(...minNumElements, SpecialValidator.elementValidationFunction...) { ... }