DEV Community

Daniel Mwakanema
Daniel Mwakanema

Posted on

One Design Pattern Per Day (Day 1); Also first post

For the why?

Well design patterns are not really a strong point of mine and naturally to get better we have to do. It will not be perfect so your criticism is welcome.

Problem for the day?

In recent times I got the chance to watch another developer work. The developer was writing an application that talks to a particular API. The API had recently undergone revisions and upper-management wanted the application to be able to talk to both versions depending on the deployment configuration.

How did the developer solve the problem?

The developer used the if control structure under each route in the application to execute the appropriate code for three versions of the API.

Perceived issues with approach?

  1. Very long and bloated functions
  2. Hard to understand code
  3. Too many levels of abstraction under each route

My thoughts?

From my point of view, the problem involves selecting an API version and from that creating the appropriate API instance. Seems like it could fall under class instantiation and object creation.

How I may have done it (the instantiation at least)?

  1. Create an interface that defines the API
  2. Have any version implement it
  3. Create a factory to create the appropriate instance given a version

So erm, the code would look like the following (there may be errors, don't care):

The interface:

  public interface API
  {
    public void doSomething();
    public void doOneMoreThing();
  }

The API instances:

  public class ApiV1 implements API
  {
    public void doSomething()
    {
      // doing something
    }

    public void doOneMoreThing()
    {
      // doing one more thing
    }
  }

  public class ApiV2 implements API
  {
    public void doSomething()
    {
      // doing something but slightly differently
    }

    public void doOneMoreThing()
    {
      // doing one more thing but slightly differently
    }
  }

The factory:

  public class APIFactory
  {
    private Map<String, API> apiMap =  Map.ofEntries(entry("v1", ApiV1),
                                                     entry("v2", ApiV2));

    public API getApiIstance (string version)
    {
      if (!this.apiMap.containsKey(version)) {
        throw new IllegalArgumentException("Passed API version does not exist.");
      }
      return this.apiMap.get(version)();
    }
  }

Usage:

  // assuming there is a config somewhere
  API apiv1 = APIFactory().getApiInstance(config.apiVersion);

Conclusion:

So erm, yeah. Not perfect but perhaps a step in the right direction.

Top comments (2)

Collapse
 
cristiangoncas profile image
Cristian

Good post!
Also good solution, waiting for the next one.

Collapse
 
jcshartz profile image
jcshartz

How would you improve upon your approach? I think it looks good already, honestly.