Programming Language independent Model Validation

2020-03-21 10:23发布

问题:

Let's say you use several different programming languages and frameworks in your infrastructure to handle large amounts of traffic etc.

Example Stack:

  1. event driven API servers (using Scala, node.js, Ruby EM)
  2. a standard full stack webapp (e.g. Rails)
  3. (maybe more technologies)

When using different languages and frameworks I usually end up duplicating most of the model validations because every "customer entry point" needs to validate its input. This is of course a pain to keep in sync.

How would you handle this without something like CORBA?

回答1:

Your best bet would be a framework that allows you to specify model validation in a language agnostic format, like JSON. You might end up with a validation schema of sorts, say:

{
  "name": [
    {
      "validate": "length",
      "minLength": 6,
      "maxLength": 10
    },
    ...
  ],
  ...
}

You would then have language-specific validators that could parse this format. The validators only need to be written once, and then you maintain a single schema for each model.

However, this is probably sounding a lot like CORBA/SOAP/Thrift/ProtocolBuffers/etc. at this point. That's because they were written to solve these types of problems, and you'll end up reinventing a few wheels if you write it yourself.



回答2:

I would go on a "dictionary" of Regular Expressions. Regular Expressions are supported by all the languages you counted - and - translating their string representation from one language to another can be done by a passing the expressions themselves through regular expressions...

To my observation - it's a lot less work then composing a parse and execute mechanism for each language...

Like advised before - you can save this "dictionary" of Reg-Exps in an agnostic format, such as JSON. This narrows down the duplicated work to -

  • one source file of validation expressions that you maintain
  • per programming language:
    • converter from the main file to the format of the target language
    • thin mechanism of
      1. reading the JSON,
      2. selecting from it the configured checks
      3. executing them
    • edge cases (if any)

Have fun :)



回答3:

To add to @Nathan Ostgard's post, XML, XSD and, when necessary, XSLT might work as well. The advantage to this would be a) XSD has the simple validation built into it b) most languages have good support for this c) you wouldn't have to write validation in each language; stuff that isn't handled in the schema could be written once in XSLT (with the caveat that XSLT implementations tend to vary :) )



回答4:

If you want to go the way of full validation, I'd use SOAP. At least, as long as you have SOAP libraries, all you need to feed them is the WSDL for your interfaces.