Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for wrapping a third party service in a library

I am interested in writing a library for a third party API I am using and I need some advice. The average use of the library will involve several api calls in one request. For example, one api call to grab a user from the third party service, and then another call to use that user to grab his/her photos. Each API call will get its own library method wrapper with additional logic to handle errors/timeouts, but my biggest question is whether the library should be made as a singleton that contains state or just as a series of class methods.

For example:

user_id = ThirdParty.get_user("[email protected]")
photos = ThirdParty.get_photos(user_id)

OR

thirdpartyservice = ThirdPartyService.new("[email protected]")
photos = thirdpartyservice.get_photos

These doesn't have to be the exact deseign of the library, but I just am confused about the pros/cons of each approach. Any help would be amazing!

Btw, I am using ruby!

like image 959
Danny Avatar asked Apr 25 '11 15:04

Danny


People also ask

Should I wrap third party libraries?

Wrapping third-party libraries is definitely a good practice to follow. It may cost you some extra time, but in the long run you are left with a system which is easier and faster to change. Robert Martin (2009). Clean Code.

Should I wrap libraries?

The decision to wrap or not to wrap depends highly on the library, sometimes it is a good idea, sometimes a very bad idea. This answer, though not wrong, leaves the impression it is always a good idea to wrap 3rd party libs - and that is definitely not a good advice.

Which design pattern will you use to shield your code from a third party library?

Adapter Pattern This provides you a way to shield or break interfaces when third party library changes something.

What does third party library means?

A third party library refers to any library where the latest version of the code is not maintained and hosted by Moodle.


1 Answers

I would have the library contain the state as this reduces the complexity of code on the user side(and that's what API are supposed to do, increase simplicity). With this approach, the user doesn't have to keep track of that user_id since the library is keeping state of that.

If the user really wanted their user_id (or any other data that the library stores), you can just create an attr_reader in your library to expose that data.

To add fleixiblity for the get_photos method, you can do something like:

class ThirdPartyService

  def get_photos(user_id=@id_stored_in_library)
    # do work
  end

end

This way it defaults to the stored id, however it adds flexibility in that the user can specify the userid if he so chooses.

like image 175
Mike Lewis Avatar answered Sep 28 '22 20:09

Mike Lewis