lundi 10 juin 2019

Pattern to break up external API calls?

I am trying to wrap my mind around how I would go about implementing this specific problem. We have an external API that performs some logic and returns back the result of that logic. Unfortunately, the API returns a new object as the result as opposed to just the part that I am interested in. For example, the code would look something like this:

public class ComplexObject {
    //lots of fields
}

public interface LogicApplier {
    LogicResult applyLogic(ComplexObject obj);
}

public class LogicResult {
    ComplexObject result;

    public ComplexObject getResult();
}

public class FirstImplementation {

    private LogicApplier _applier;

    public Implementation(LogicApplier applier) {
        _applier = applier;
    }

    public ComplexObject mainImplementation (ComplexObject apply) {
        LogicResult logicResult = _applier.applyLogic(apply);

        ComplexObject newComplexObject = logicResult.getResult();

        //Do some other stuff with new ComplexObject
    }
}

So question is: what would be the best way to put a limit on LogicApplier's "power" over FirstImplementation? For example, our motivation to call logic in the first place is to derive a missing field, let's say "name". This field could potentially be different in, say, SecondImplementation where that implementation is now looking to derive "street address" from LogicApplier API. However, there is nothing to stop LogicApplier from changing some other field, say "idNumber".

Is this best solved by a adding an interface for our specific implementations and manually mapping fields? Something like:

public interface SecondImplementationLogicApplier {

    public String deriveAddress(ComplexObject o);
}

public class LimitedImplementationLogicApplier implements FirstImplementationLogicApplier, SecondImplementationLogicApplier {
    LogicApplier _applier;
    public LimitedImplementationLogicApplier(LogicApplier applier) {
        _applier = applier;
    }

    public String deriveFirstName(ComplexObject o) {
     LogicResult res = _applier.applyLogic(o);
     return res.firstName;
    }


    public String deriveFirstName(ComplexObject o) {
     LogicResult res = _applier.applyLogic(o);
     return res.address;
    }

}

Aucun commentaire:

Enregistrer un commentaire