Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Streamline the validation of arrays of objects #281

Open
javagl opened this issue Sep 27, 2023 · 0 comments
Open

Streamline the validation of arrays of objects #281

javagl opened this issue Sep 27, 2023 · 0 comments

Comments

@javagl
Copy link
Contributor

javagl commented Sep 27, 2023

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 number or object)

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...) { ... }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant