Reputation: 141
I wrote this method that takes in a generic parameter object. This method accepts different parameter objects with different properties. The idea is that based on the value of the "MethodName" property, I can construct a URI base on properties of that particular parameter object
I use reflection to get the value of the property named "MethodName." It's not a method, just a property name.
I use the value of the MethodName property in a case statement. This seems like an inferior way to accomplish my task. Especially as the number of MethodNames grow.
Below is the source with the case statement implementation. Any help would be appreciated.
public string ConstructBBAPIUri<T>(T parameters)
{
var methodName = "";
var uri = "";
var userId = "";
long timeStamp = 0;
var signature = "";
var sessionKey = "";
var newUserId = "";
if (parameters != null)
{
methodName = parameters.GetType().GetProperty("MethodName").GetValue(parameters, null).ToString();
switch (methodName)
{
case "user.login":
userId = parameters.GetType().GetProperty("UserId").GetValue(parameters, null).ToString();
timeStamp = Convert.ToInt64(parameters.GetType().GetProperty("TimeStamp").GetValue(parameters, null));
signature = GenerateBunchBallSignature(userId);
uri = "method=" + methodName + "&apiKey=" + apiKey + "&userid=" + userId + "&ts=" +
timeStamp + "&sig=" + signature;
break;
case "user.modifyUserId":
//We shouldn't need the session key if user.login is being called first
userId = parameters.GetType().GetProperty("UserId").GetValue(parameters, null).ToString();
newUserId = parameters.GetType().GetProperty("NewUserId").GetValue(parameters, null).ToString();
uri = "method=" + methodName + "&sessionKey=" + sessionKey + "&oldUserId=" + userId +
"&newUserId=" + newUserId;
break;
}
}
return uri;
}
Upvotes: 0
Views: 724
Reputation: 619
A better design would be to delegate constructing of URI on the classes.
Upvotes: 4
Reputation: 5672
An option would be to add functions to a dictionary but I don't see how that would be much better than the current method, and it would be more confusing and error-prone.
I think what Max Shmelev is hinting at would be the best solution. If you can, add an interface to each class which will be passed, and add a generic constraint to this method. The interface will define a method which, when implemented in the objects, will handle the serialization for that object.
If the list isn't too much longer, you could add methods for each different type to be handled, and just have a single method call within each case.
Upvotes: 0