mercredi 13 septembre 2017

Inheritance pattern for input check?

I have a bunch of classes that get similar input and return similar output. It makes sense to have a parent class do basic sanity check on the input and let the child classes determine specific output.

Does the current implementation of the parent class (below) look sufficiently maintainable and extendable? Could i maybe improve the code using a design pattern?

If a child class now wants to do its own, extra, sanity check on the input, there are two places this can happen: testInputAndCreateOutput and in createOutput. I think there should be one place and it should be obvious.

public OutputSuperClass doSomeFancyStuff(InputSuperClass input) {
    OutputSuperClass output = testInputAndCreateOutput(input);
    if (output.hasError()) {
        return output;
   } else {
         // do all the fancy stuff, return output
   }
}

protected OutputSuperClass testInputAndCreateOutput(InputSuperClass input) {
   OutputSuperClass output = createOutput(input);
   testInputAndAdjust(input, output);
}

/**  Child classses implement this
*/
protected abstract OutputSuperClass createOutput(InputSuperClass input);

private void(InputSuperClass input, OutputSuperClass output) {
  //check input, set errors on output if something wrong with input
}

Aucun commentaire:

Enregistrer un commentaire