Using Decorator πŸŽ€ and Builder πŸ›  patterns on an APIClient πŸŽ„

Rodrigo Cavalcante
3 min readOct 24, 2018

--

Almost every mobile application need internet to do something like update user info, check for news, save a game data and more. So we can say it is an important part of our app.

I usually use Alamofire to do this job and it is a good practice wrap external libraries so we will be able to change them any time and believe me this time will come.

A wrap can be done by creating a protocol. So let's create a simples APIClient that will receive parameters, headers, and method to perform a request.

Below you can see an example of this APIClient

APIClient example code

This APIClient do a lot of stuff like check for internet connection, handle an error, and do a request. It can do a lot more like injecting custom headers on each request or handle invalid token to refresh it. Imagine our APIClient doing all of this stuff. It will get bigger, confuse, and unmaintainable.

It is common to find a class that does a lot of stuff, doing more things that it is responsible for. And this goes against the single responsibility principle from SOLID.

So we can use the Decorator pattern to make our APIClient smaller and more specific.

The decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other objects from the same class.

In the example above we can break our APIClient functions in three:

  • Check for internet connection;
  • Handle error;
  • Do our request.

A Decorator must have a reference to another object of the same type, that object will be decorated. The objective of this patterns is to add a behavior to another object without the need to modify its class.

So we can refactor it into two decorators. One to check for internet connection and the second one to handle errors.

After that, we refactor our APIClient to a RequestAPIClient

Our final apiClient will be a mix of Decorators . Our ReachabilityAPIClient will request our ErrorHandlerAPIClient which will request our RequestAPIClient. When the server returns a response, first will be handled by our RequestAPIClient than ErrorHandlerAPIClient and finally our ReachabilityAPIClient.

The way we build our apiClient object can be a bit confusing and easily anyone can make a mistake and forget to use a decorator e.g. forget to add the behavior of handling errors. So we can create a builder to help our developers decide which behavior they will add to the apiClient object.

The Builder is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from its representation.

Ps: If you like this post, share it on Twitter, recommend it on medium, or both =). This really helps me to reach more people. Thanks a lot.

--

--