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!
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.
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.
Adapter Pattern This provides you a way to shield or break interfaces when third party library changes something.
A third party library refers to any library where the latest version of the code is not maintained and hosted by Moodle.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With