How can I keep complex business logic outside of an orchestrator method (using SRP and clean architecture ideas)?

I am trying to refactor some orchestrator code. The orchestrator calls multiple APIs and then parses/transforms the responses, gathers them together and returns them.

One of the API calls returns a Response which is then parsed into 3 distinct fields.

public OrchestratorResponse doSomething() {
    // The focus of the question
    ApiResponse response = callApi();
    A a = parseToA(response);
    B b = parseToB(response);
    C c = parseToC(response);

    // Just here for illustration purposes
    OtherResponse otherResponse = callOtherApi();
    D d = parseToD(otherResponse);

    return new OrchestratorResponse(a, b, c, d);
}

As part of my refactoring, I am thinking of using a Repository pattern so that the Orchestrator doesn't need to think about calling the APIs and parsing (the single responsibility principle). I would also like to keep business logic like parsing etc. outside of this method.

public class DRepository {
    public D getD() {
        OtherResponse otherResponse = callOtherApi();
        return parseToD(otherResponse);
    }
}

However, this isn't so clean with the first bit of code, since it will need to return a, b and c, and therefore needs a nested class.

public class FirstApiRelatedFieldsRepository {
    public FirstApiRelatedFields getFirstApiRelatedFields() {
        ApiResponse response = callApi();
        A a = parseToA(response);
        B b = parseToB(response);
        C c = parseToC(response);
        return new FirstApiRelatedFields(a, b, c);
    }

    class FirstApiRelatedFields {
        A a;
        B b;
        C c;

        // constructors and getters
    }
}

public OrchestratorResponse doSomething() {
    FirstApiRelatedFields firstApiRelatedFields = firstApiRelatedFieldsRepository.getFirstApiRelatedFields();

    D d = dRepository.getD();

    return new OrchestratorResponse(
        firstApiRelatedFields.getA(), 
        firstApiRelatedFields.getB(), 
        firstApiRelatedFields.getC(), 
        d
    );
}

What is the best thing to do in this case, keeping in mind readability, clean code, clean architecture and SRP? Keep the api call and the parsing in the orchestrator method? Or use the repository pattern? Or a third thing?

Thanks in advance.



Read more here: https://stackoverflow.com/questions/68464390/how-can-i-keep-complex-business-logic-outside-of-an-orchestrator-method-using-s

Content Attribution

This content was originally published by ryuu at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: