lundi 27 novembre 2017

Elegant pattern for validating a set of input parameters in java

I'm struggling to find an elegant solution to a validation problem. the problem looks like this.

I have a set of input parameters: p1, p2, p3, p4 (They are received as key value pairs, type Object). Each parameter can have multiple predefined values and only a few combinations are valid. Examples of valid combinations:

  • p1=Va, p2=Vb, p3=V123, P4=Vabc
  • p1=Vb, p2=Vb, p3=V123, P4=Vabc
  • p1=Vc, p2=Vb, p3=V123, P4=Vxyz (where all Values Vxxx are predefined constants)

If the valid combinations would be static, I would create a holder class and create of static collection with all possible combinations of parameters.

But, in some cases one of the parameter could vary, and still be a valid data set. For example: P1 could be predefined constant, or could be some arbitrary numeric ID. In this case a valid set of data would be:

  • p1=[any numeric value], p2=Vn, p3=V123, P4=Vnnn

In this case, how can I validate such set of parameters, in which one could take any value and be valid.

I considered a few options but none I would like: 1. describing matching conditions with classic if else statement. not clear enough. Plus, At some point I need a mapping between my predefined combinations to an output constant. 2. I could have a custom equals method in my holder, but I don't like this approach. More, I'm trying to find a generic approach. What if the number of parameters would increase very much, and the number of variable parameters as well.

PS. I could separate the validation in half and do match first the constant parameters, but please remember that one of them can have either predefined constants either arbitrary numbers

Thank you!

Aucun commentaire:

Enregistrer un commentaire