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?
The factory is typically where you place the switch statement to handle the different types. In a parser, you might have levels of responses and types to deal with, so they get stacked: if a “purchase” response comes back, it might include the shipping address so you’d use the factory to create a purchaseHandler which would handle the shipping addresses, item weights, etc.; if a refund response comes back the factory could return a refundHandler which would handle the refund amount, etc.
It would be nicer if the RESTful api would only return the type you requested, but not all apis follow the Interface Segregation Principle. So you sometimes have to deal with messy data.