0

I have a function a plugin that is called whenever the WebAPI's "Plugin" endpoint is called in the main project, and that has to process the HTTP request. The request holds more information about what to do in method and query string, and I have for now copy&pasted the code to choose methods based on these:

public object OnCustomControllerCalled(Toolkit tk, HttpRequestMessage req)
{
    if (req.Method == HttpMethod.Get)
    {
        if (req.RequestUri.Query.Contains("data=Customers"))
        {
            return MyPlugin.GetCustomers(tk);
        }
        else if(req.RequestUri.Query.Contains("data=UserManagement"))
        {
            return MyPlugin.GetUserManagement(tk);
        }
        ...
    }
    else if (req.Method == HttpMethod.Post)
    {
        if (req.RequestUri.Query.Contains("data=Customers"))
        {
            return MyPlugin.PostCustomers(tk, req);
        }
        else if(req.RequestUri.Query.Contains("data=UserManagement"))
        {
            return MyPlugin.PostUserManagement(tk, req);
        }
        ...
    }
    else if (req.Method == HttpMethod.Put)
    {
        if (req.RequestUri.Query.Contains("data=Customers"))
        {
            return MyPlugin.PutCustomers(tk, req);
        }
        ...
    }
    else if (req.Method == HttpMethod.Delete)
    {
        ...

I know that copy&paste is not a good approach to this problem. How am I supposed to make this easily extensible and less error-prone?

Throw reflection at it to get to the DRY principle?

Or would it make sense to have a single function MyPlugin.Customers instead of one for each method, and let that single method contain the whole behaviour regarding the "customer" objects, and keep the differentiation between get, post, put and delete in that function?

1

1 Answer 1

3

You can use an inheritance based approach for this.

Example:

public abstract class HttpAction
{
  public void Get();
  public void Put();
  public void Post();
  public void Get();
}

public class HttpActionFactory
{ 
  public void Get(string uri)
  { 
    if(uri.Contains("Customers")) return new CustomerHttpAction();
    //...
  }
}

public object OnCustomControllerCalled(Toolkit tk, HttpRequestMessage req)
{
  var action = HttpActionFactory.Create(req.RequestUri);
  if(req.Method == httpMethod.Get()) return action.Get();
  //...
}

If you want to add something other than customers or users, you no longer have to change the OnCustomerControllerCalled method.

You can add a new class inheriting from HttpAction and extend the Factory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.