I am trying to build an application that handles making lots of API requests to 2 or 3 related APIs. My general strategy is to have one base class ApiRequest that has:
List<Parameter> Parameters
Uri CombinedUri
string Results
string _Host
and methods:
CombineUri() //combines the _Host and parameters into full Uri
MakeRequest() //makes the request and stores Results
Then I would inherit that base class into many different Api Calls and implement functions in those specific to that Api call.
The problem I have is that I call CombineUri() in my base classes constructor, but it requires that _Host already be set. However, I want _Host to be a constant in each child class since it is specific for each different Api call. I do not want to have to remember to call CombineUri from every derived class’ constructor.
Any ideas to get around that problem would be greatly appreciated. Also, if you have a different design idea entirely for implementing a base for Api calls I would be all ears. I am not sure my approach is the best.
Thanks.
My Solution:
I implemented ideas from both John and Colin Pear.
I changed the base ApiRequest into an abstract class, and I moved the CombineUri() method into the MakeRequest() method.
I also went further and changed ApiRequest into a generic class and changed _Host into a static string. This way, each subclass with subclass ApiRequest<*subclassname*>. Due to the properties of generics, each object of a particular subclass will share a static _Host.
How about making CombineUri() private and then call it inside the implementation of MakeRequest().
The user of this class should not have to know that they need to call two methods, and furthermore, that they have to call CombineUri before they call MakeRequest. That’s an implementation detail that belongs inside MakeRequest.
It’s possible I don’t fully understand the classes, but if I do, then I would make CombineUri private and always call it as the first part of MakeRequest.