mercredi 14 août 2019

Implementing Factory Patterns - Removing the switch

I've recently just started trying to improve my base skills as a developer and reading more about Design Patterns, and a variation of an Abstract Factory is something I've been using for a little while. I have a question on the specifics of implementation though, namely removing the need for a big switch statement.

Let's assume I have a REST API for inputting types of Document into a database. All the types of documents inherit from an Document abstract class.

public IDocumentFactory{
    Document CreateDocumentTypeOne(string inboundDocumentJson);
    Document CreateDocumentTypeTwo(string inboundDocumentJson);
}

How do I get away from doing something like this in my API controller to decide which type of document is coming in

public Document LoadDocument (string type, string inboundDocumentJson) {
    switch (type) {
        case "type1":
            return IDocumentFactory.CreateDocumentTypeOne(inboundDocumentJson);
        case "type2":
            return IDocumentFactory.CreateDocumentTypeTwo(inboundDocumentJson);
    }    
}

I feel like whichever way I implement the code I'm going to need a switch statement like this somewhere? Whether that be having different API endpoints and the switch lying before I make the call to the API? Or in the API somewhere.

Am I missing something regarding the implementation? And if not, where is the optimal place to put the code?

Aucun commentaire:

Enregistrer un commentaire