samedi 16 septembre 2017

Design pattern(Java): Multiple classes, same field set

Consider a Java program that includes 3 classes: Entry, Validator, and Context. Validator has a method boolean isValid(Entry entry, Context context), which will determine the validity of an entry object based on a context. Validator can either be set to check each entry.field against a preset specific value (i.e. MatchingMode.SPECIFIC) or against the value of the corresponding field from Context (i.e. MatchingMode.CONTEXT). MatchingMode is a nested enum within Validator class. Consider the following pseudo code for further elaboration:

Validator::boolean isValid(Entry entry, Context context)
{
    boolean valid = true;
    for(each field):
        if(this.field.matchingMode == MatchingMode.SPECIFIC)
            valid &= (entry.field.equals(this.field));
        else if(this.field.matchingMode == MatchingMode.CONTEXT)
            valid &= (entry.field.euqals(context.field));
    return valid;
}

Notes:

  • All validator objects are created in the beginning of the code's execution and will persist until its termination.
  • Entries are user's input to the program and will continually be fed to the code.
  • Context objects will be created based on the entries.
  • Fields have different types.

Given the above validation use case, how do you suggest implementing this code in a DRY and type-safe manner?

Aucun commentaire:

Enregistrer un commentaire