I came across Instagram’s API client written in Python.
In their class InstagramAPI, they bind the methods to a function in bind.py. When called, the function returns an instance of the class InstagramAPIMethod and execute the request call.
- What are the advantages of doing it this way? (over directly creating instances of InstagramAPIMethod in InstagramAPI)?
- What will happen if the methods in InstagramAPI are called numerous times? Will it create new a instance every call?
Note, the only advantages I thought of are (probably I’m off track):
- The class doesn’t/shouldn’t care what the implementing class is.
- If a particular method is not called, we will never create an instance.
2
One of the tags on this question gives you an idea of what the answer may be. This is a common design pattern, particularly for services, and very common for web services.
Basically, they’re hiding the instantiation of the InstagramAPIMethod and keeping it all in one spot. This allows for flexibility internally so they can change how things work under the hood while ensuring bind_method keeps working the same way.
In addition, this makes it easy to change and update to new URLs, new methods, and so on. This is why it gets used so widely with web services – the cost of updates and changes is very minimal.
I think in this way you have all the instantiations of that class centralized in only one place ( bind_method() ).
So if you have to make any change related to the constructor or the _call method signature or whatever you have to modify your code in only one place, otherwise you should try to find every line of code where you are making an instantiation of the class and calling _call method an modify it.
Hope this helps.
Benefit of Dynamic binding is that we can tell the compiler that here is the possibility to exist more subclasses of this class and the method can be over ridden there so please leave it for future refrence, otherwise compiler bind it to the present call and our next over riding for this method will not produce the desired result.